When following TDD, using mocking tools like RhinoMocks (here) or NMock (here) is a critical part of the process. By utilizing mocking tools you can better isolate your tests to only test the code that you have direct control over. This can prove to be critical component to building out your test suite.
One thing that I have found fairly poorly documented about mocking is how to mock void methods. Today I thought I would give a quick how-to on how to mock voids. My mocking tool of choice is RhinoMocks, so the code below will be specific to that mocking framework.
Mocking voids is really not that much different then mocking methods with return values. Except for one slight thing, you actually have to make a call to your method on your mock, then setup the expectation on that call. Below I will put the code to mock non-void methods, then to mock void methods just to show the differences.
Mocking non-void methods
- MockRepository mocker = new MockRepository();
- ISomeObject someObjectMock = mocker.CreateMock<ISomeObject>();
- Expect.On( someObjectMock).Call( request.IsRequestValid() ).Return( true );
- mocker.ReplayAll();
- .... Make some call that will exercise your mocks
- mocker.VerifyAll();
Mocking void methods
- MockRepository mocker = new MockRepository();
- ISomeObject someObjectMock = mocker.CreateMock<ISomeObject>();
- someObjectMock.SomeVoidMethod(0, "", "" );
- LastCall.IgnoreArguments();
- mocker.ReplayAll();
- .... Make some call that will exercise your mocks
- mocker.VerifyAll();
You will notice that the two different methods are pretty much the same EXCEPT for lines 3 & 4 in the void methods. When mocking void method you need to actually make the call on the mock object for the method you expect to call later in your test. This will setup the call inside the mocking framework. The next step is to use the 'LastCall' (some info here) object. The LastCall object is used ONLY for mocking void methods. Unlike the 'Expect' object you do NOT need to provide the object that the void method is on, you only need to setup the expectations for the call. This includes things like the number of calls or the types of arguments for the call.
Mocking voids is no more complicated then non-voids, but it does require a little more work and the use of different objects.
I hope this helps.
Till next time,