Posts

Showing posts from September, 2011

RhinoMock to return different value based on method parameter

How do you return different values based on different parameter in a mocked object using RhinoMock?

Maybe there are other ways of doing the same thing. These are the two methods that i know.

Lets say i have the following interface that i wanna mock.
public interface ITest { int Test(string data); }

[TestMethod] // Method #1 public void ExpectConditionalMethodInputParameter()
{
var mock = new MockRepository();
var subject = mock.DynamicMock();
int result;

With.Mocks(mock).Expecting
(
delegate
{
Expect.Call(subject.Test(Arg.Is.Equal("1"))).Return(100).Repeat.Any(); // Set expectation input parameter1
Expect.Call(subject.Test(Arg.Is.Equal("2"))).Return(200).Repeat.Any(); // Set expectation input parameter2
}
).Verify(
delegate
{
result = subject.Test("2"); // Returns 200 if parameter is 2, return 100 if parameter is 1
}
);
}


[TestMethod] // Method 2 public…

Efficient way of representing Date

What is an efficient way of representing date?

Try the following code (Taken from Art of Computer Programming Vol 4)

var y = 2012; // Year 2012
var m = 6 // June
var d = 30 // 30th day on the calendar month


// Efficient representation (packing)
var result = (((y << 4) + m) << 5) + d;


Breaking this down further, we have

(y << 4)
Binary representation for 2012 is : 11111011100
Left shift by 4 : 111110111000000

Next we have,

((y << 4)+ m

111110111000000 + 110 (m = 6) = 111110111000110
Left shift 5, becomes 11111011100011000000

Next we add the days to it which bring us to the following equation

11111011100011000000 + 11110 = 11111011100011011110 ( Decimal : 1030366)

So our final result is : 1030366

// Unpacking
var day = result%32;

1030366 % 32 = 30 (once you have this, the rest is pretty straight forward)


var month = (result >> 5) %16;
var year = result >> 9;

Is there any other alternative for doing this? Maybe for other data types such as telephone.