Tuesday, 8 September 2009

Assert that a method was called with Rhino Mocks

This is not all that hard or difficult to figure out on your own, but hopefully it helps someone who’s stuck.  If you want to test that a method was called with Rhino Mocks, it’s easy!

Usually you want to assert that a method was called if you’re testing one class that has to call another.  This is particularly useful when testing the repository pattern and you want to ensure that it’s calling your data context’s submit changes method.  You will have to mock the data context for this to work, and of course you’ll need to wrap your data context in an interface, but that’s a post for another day.  I’ll post a link when I do it.

   1: MockRepository mocks = new MockRepository();
   2: IDataContextWrapper context = mocks.DynamicMock<IDataContextWrapper>();
   3: mocks.ReplayAll();
   5: IWebProxyRepository target = new WebProxyRepository(_Proxies.AsQueryable(), context);
   6: target.Delete("", 200);
   8: context.AssertWasCalled(c => c.DeleteOnSubmit(_Proxies[0]));
   9: context.AssertWasCalled(c => c.SubmitChanges);

It’s pretty straight forward.  If you’re not sure what parameters were used, or don’t care, or if you want to assert that it was called a certain number of times you can use the options that are available ot you when you setup your results like so:

   1: context.AssertWasCalled(c => c.DeleteOnSubmit(_Proxies[0]), o => o.IgnoreParameters().Repeat.Times(2));

No comments: