Using Rhino Mocks with Void (or ‘Sub’) Methods
I ran into a bit of trouble the other day when I was writing a test with Rhino Mocks. It took a while to find the solution, so I figured I’d post it here for anyone else looking to do the same thing.
The problem I had was trying use a mock object for my data access layer, and calling a void method on the class. There are thousands of examples of how to mock a method call that returns a value, but it took a while to find out how to handle a method call that doesn’t return anything. In my test below, if the method returned something, I’d use code like this:
{
Expect.Call( dal.ExecuteQuery( null ) ).IgnoreArguments().Return( results );
}
For a void method (or ‘Sub’, instead of ‘Function’, for the VB.Net developers), you need to set up a delegate instead. See the line that calls “ExecuteNonQuery” for an example.
public void CreateNewUserStory()
{
MockRepository mockery = new MockRepository();
IDataAccessor dal = mockery.CreateMock<idataaccessor>();
IUserStoryControl screen = mockery.Stub<iuserstorycontrol>();
UserStoryController controller = new UserStoryController( dal );
screen.StoryTitle = “Test title”;
screen.Description = “Test description”;
using ( mockery.Record() )
{
Expect.Call( delegate { dal.ExecuteNonQuery( null ); } ).IgnoreArguments();
}
using ( mockery.Playback() )
{
controller.CreateNewUserStory( screen );
}
Assert.AreEqual( “”, screen.StoryTitle );
Assert.AreEqual( “”, screen.Description );
}