marthijn. Rotating Header Image

Using Rhino Mocks to mock a void function

In some of my web applications I use Rhino Mocks to create mock objects. Usually the code has a record section where the expected calls are recorded, and a playback section where the testing is done. In the following code snippet the DoSomething() function calls a void function which is defined in the interface of _myMock. The problem is this void function is not expected and the NUnit test run will fail:

Rhino.Mocks.Exceptions.ExpectationViolationException : IMyInterface.MyVoidFunction; Expected #0, Actual #1.
using (_mock.Record())
{
  Expect.Call(_myMock.GetValue("a")).Return("b");
  /* insert expectation for void function here */
}
 
using (_mock.Playback())
{
  // DoSomething calls the mocked object's GetValue function, which returns 'b' when the parameter is 'a'
  // DoSomething also calls a void function which is located in the interface of the mocked object, so this
  // void function must be mocked too, else the test run will fail
  Assert.AreEqual("b", _myObject.DoSomething("a"));
}

When trying to create an expectation for this void function Visual Studio will give a syntax error:

Expect.Call(_myMock.MyVoidFunction()); // Argument '1': cannot convert from 'void' to 'Rhino.Mocks.Expect.Action'

On the internet I found two solutions to fix this problem. The first solution uses a delegate:

Expect.Call(delegate{ _myMock.MyVoidFunction(); });

The second solution uses a lambda:

Expect.Call(() => _myMock.MyVoidFunction());

Now the test will succeed.

Leave a Reply