Jul 6, 2010

Cleaner Mocking with NSubstitute

Rhino Mocks is a great mocking framework, being seen as one of the best ones around and rightly so, however it’s syntax at times is a little verbose and clunky.

A few of the guys from the Sydney Alt.Net group who work together at Cochlear got a little fed up with the syntax Rhino uses for creating and managing mocks and figured there must be a better way.  A different approach that will give them much cleaner code.  As a result they’ve gone and created a project to produce a clean API for mocking and released it as an open sourced project called NSubstitute.

For example, consider the following two code samples:

[Fact]
public void Rhino_MethodWasCalled()
{
var monkey = MockRepository.GenerateMock<IMonkey>();
var keeper = new ZooKeeper {AssignedMonkey = monkey};
monkey.Stub(m => m.CurrentFleaCount()).Return(0);

keeper.CleanMonkey();

monkey.AssertWasCalled(m => m.CurrentFleaCount());
monkey.AssertWasNotCalled(m => m.Clean());
}

versus the equivalent test in NSubstitute

[Fact]
public void NSubstitute_MethodWasCalled()
{
var monkey = Substitute.For<IMonkey>();
var keeper = new ZooKeeper { AssignedMonkey = monkey };
monkey.CurrentFleaCount().Returns(0);

keeper.CleanMonkey();

monkey.Received().CurrentFleaCount();
monkey.DidNotReceive().Clean();
}

In particular, not the way mocks are created, the way a method is stubbed and how the asserts are performed.  The NSubstitute version has less code to create the mock and doesn’t require lambda’s for either the method stub or the asserts making it much more readable.  I’m finding it much nicer to use than Rhino’s syntax and for me less typing and better readability is always a good thing :-)

There’s a lot of other things that the guys have done to make mocking cleaner and I’d strongly recommend you get yourself over to the NSubstitute project site on GitHub, check out the other features and have a play.  There’s still a few rough edges and features to be implemented but the majority of usage scenarios are covered so it’s very much usable for day to day work right now. By the way, Dave Tchepak announces NSubstitute and shows a few more usage examples on his blog, which you should also go and have a look at.

Congratulations to both Dave Tchepak (@davetchepak) and Anthony Egerton (@guywithbeard) for getting this thing together.  Well done, and I hope this project really takes off :-)

1 comment:

  1. Thank you, Richard, for introducing me to NSubstitute! For a rusty old programmer like myself, NSubstitute is a God-send! After messing about with Rhino Mocks for ages, NSubstitute just works. Hooray for well-designed software!

    ReplyDelete