views:

67

answers:

1

I currently have interfaces much like the following:

interface IService
{
   void Start();
   IHandler ServiceHandler { get; }
}

interface IHandler
{
   event EventHandler OnMessageReceived;
}

Using Rhino Mocks, it's easy enough to mock IService, but it doesn't assign any IHandler instance to the ServiceHandler property. Therefore when my method under test adds an event handler to _mockedService.ServiceHandler.OnMessageReceived, I get an 'Object reference not set' error.

How can I ensure that ServiceHandler is assigned a value in the mocked IService instance?

This is likely Rhino Mocks 101, but I'm just getting up to speed on it...

+4  A: 
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 older 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
}
Lee
I'm guessing RM 3.3 (which I'm stuck using unfortunately) doesn't support the extension method syntax you've got there - any idea on the 3.3 syntax to achieve the same thing?
Marcus