I’ve recently started using RhinoMocks instead of nMock, mainly because it’s strongly-typed. However, I’ve found a few other little treats:
Stubs
In nMock, if you want to stub some method calls on a mocked interface you have to do something like this:
Mockery mockery = new Mockery();
IService mockService = mockery.NewMock();
Stub.On(mockService).Method("MethodA");
Stub.On(mockService).Method("MethodB");
Stub.On(mockService).Method("MethodC");
...
Which is cumbersome and noisy. In RhinoMocks you can do this:
MockRepository Repository repository = new MockRepository();
IService serviceMock = repository.Stub();
...
…and RhinoMocks will ignore all calls to that interface. This is really nice as you generally only test the SUT’s interaction with one dependency at a time.
Dynamic Mocks
If you only want to test one interaction with a dependency and ignore all others you can create a dynamic mock.
MockRepository Repository repository = new MockRepository();
repository .DynamicMock();
...
All calls to the mocked dependency will be ignored unless they are explicitly expected (e.g. Expect.Call(mockService.MethodA)…..). This is the same as not saying mockery.VerifyAllExpectationsHaveBeenMet() in nMock. It’s always annoyed me that you have to remember to do this in nMock and I much prefer that the default for RhinoMocks is to fail when encountering an unexpected method call.
Raising Events
nMock does not natively support raising events, which is a pain, but there are ways around it (I’ve extended his example to support custom EventArgs which you can download here). With RhinoMocks it’s much simpler. Rather than explaining it myself, check out J-P Boodhoo’s great example here.
If you’re talking about NMock2 (not nMock) then event firing *is* there.
The test for the case described by Neil (http://blog.gravityfree.ca/2007/03/raising-events-in-nmock-20.html, I’ve put a comment there as well) would go as
[Test]
public void ShouldLoadAccountsIntoViewOnPageLoad()
{
var mockery = new Mockery();
var view = (IAccountSummaryView)mockery.NewMock(typeof(IAccountSummaryView));
Expect.Once.On(view).EventAdd(“Load”);
Expect.Once.On(view).Method(“Display”).With(Is.Anything);
var presenter = new AccountSummaryPresenter(view);
Fire.Event(“Load”).On(view).With(null, null);
mockery.VerifyAllExpectationsHaveBeenMet();
}
On a general note – unfortunately, nMock is no longer supported. Those of us who really like the expectations DSL and syntax of nMock are probably better off moving over to NMock2.
Or choose Rhino Mocks or Moq or Typemock Isolator 🙂
Cheers,
Andrew
I was talking about nMock. This article was written pre NMock2 so I guess it’s now irrelevant.