Can I define implementation of methods on Rhino Mocked objects?
With Rhino.Mocks, once I Mock an Interface I can:
- Set up "return" values for non void methods on the mocked object
- Inspect how and with what values certain methods were called with
However, is it possible to selectively define an Implementation for methods on mocked objects?
Ideally I'd like to do this (RhinoImplement is the Rhino extension I'm hoping exists!):
var messages = new List<IMessage>();
IBus bus = MockRepository.GenerateMock<IBus>();
bus.RhinoImplement(b => b.Send(Arg<IMessage>.Is.Anything), imess => messages.Add(imess));
//now run your test on the Class that uses IBus
//now, I can inspect my local (List<IMessage>)messages collection
Update with Answer
Thanks to Patrick's answer below开发者_如何学编程, the correct code to achieve the above is:
var messages = new List<IMessage>();
IBus bus = MockRepository.GenerateMock<IBus>();
bus
.Expect(b => b.Send(Arg<IMessage>.Is.Anything))
.WhenCalled(invocation => messages.Add((IMessage)invocation.Arguments[0]))
.Repeat.Any() //the repeat part is because that method might be called multiple times
//now run your test on the Class that uses IBus
//now, I can inspect my local (List<IMessage>)messages collection
Use the "WhenCalled" method:
Rhino Mocks - Set a property if a method is called
The following code works using a Rhino stub instead of a Mock. To stub out a method with side-effects.
private IGuy DefaultDood()
{
var guyStub = MockRepository.GenerateStub<IGuy>();
guyStub.Expect(u => u.DrinkHouseholdProducts(Arg<string>.Is.Anything)).WhenCalled(invocation =>
{
guyStub.JustDrank = ((string)invocation.Arguments.First());
guyStub.FeelingWell = false;
}
);
return guyStub;
}
精彩评论