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.


Related posts:

  1. Using NUnit in Visual Studio 2010
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

2 Comments

  1. Do you need some special type of extension for the Call method for this to work? I can’t use lambdas or delegate.

  2. Marthijn says:

    For delegates you need to use the System namespace, see http://msdn.microsoft.com/en-us/library/system.delegate%28v=vs.80%29.aspx
    Does that solve your problem?

Leave a Reply