Mock non-installable child property with Rhino Mocks
I currently have interfaces similar to the following:
interface IService
{
void Start();
IHandler ServiceHandler { get; }
}
interface IHandler
{
event EventHandler OnMessageReceived;
}
Using Rhino Mocks it is easy enough to fool the IService, but does not assign an instance to a IHandler
property ServiceHandler
. So when my tested method adds an event handler to _mockedService.ServiceHandler.OnMessageReceived
, I get an "Object reference not set" error.
How can I ensure that the ServiceHandler gets assigned a value in the laughing instance IService
?
It's probably Rhino Mocks 101, but I'm just getting up to speed ...
a source to share
IService service = MockRepository.GenerateStub<IService>();
IHandler stubHandler = MockRepository.GenerateStub<IHandler>();
service.Stub(s => s.ServiceHandler).Return(stubHandler);
//assertions
Or you can use GenerateMock instead if you need to record expectations on your fakes.
EDIT: For earlier versions of RhinoMocks, you can do this:
MockRepository mocks = new MockRepository();
IService service = mocks.CreateStub<IService>();
IHandler handler = mocks.CreateStub<IHandler>();
using (mocks.Record())
{
SetupResult.For(service.ServiceHandler).Return(handler);
//setup expectations using Expect.Call
}
using (mocks.Playback())
{
//assertions
}
a source to share