views:

30

answers:

1

Using RhinoMocks - how can I say "whenever some function is called from now on - it should return some value".

I'd like to say something like this:

fakeCalculator.WhenCalled(factory => factory.AddNumbers(1, 2)).Return(3); 

And then - when the AddNumbers function is called with 1 and 2 - it will return 3. I.e. I want to define this ahead, and then trigger the function. The reason is that I depend on this behavior for my mock which is injected into another class - which will again call the AddNumbers function.

+1  A: 

Something like this:

MockRepository mocks = new MockRepository();
IFactory factory = mocks.DynamicMock<IFactory>();

using(mocks.Record()) {
    factory.AddNumbers(1, 2);
    LastCall.Return(3);

    factory.AddNumbers(2, 3);
    LastCall.Return(5);
}

int result = factory.AddNumbers(1, 2);
Assert.AreEqual(3, result);

result = factory.AddNumbers(2, 3);
Assert.AreEqual(5, result);
Jason
Exactly like this. Thx! Haven't used the Record function before..
stiank81
@stiank81: It's a pretty sweet feature. You can also say `LastCall.Throw(someException)` or `LastCall.Do(someDelegate)` to really have some fun.
Jason
Cool, thx Jason! Still some good stuff to learn in Rhino apparently! :-)
stiank81