Friday, January 7, 2011

RhinoMocks: execute a specific action when a method is called

When writing unit tests sooner or later you are confronted with mocking. I always try to keep my mocking code as simple as possible. Sometimes this means creating a mock object manually and sometimes it means using a mocking framework. The mocking framework I use the most is RhinoMocks created by Ayende Rahien.

Last week I had to mock a call to a specific method and execute some code when this method is called to test some specific behavior. Creating a mock object myself for this would be rather cumbersome, with Rhinomocks this becomes really simple:

   1:  var repository=MockRepository.GenerateMock<IDeliveryRepository>();
   2:  repository.Expect(rep => rep.ReadDeliveryData(null, null))
   3:                        .IgnoreArguments()
   4:                        .Do(new Action(()=>task.Process(data, delivery)));

It’s important that the code you execute in the Do() matches the signature of the method that is called in the Expect(). The first time I implemented this the test failed with the following error message:

“Callback arguments didn't match the method arguments.”

because the code I executed in the Do() didn’t match.

No comments: