Mocking with NSubstitute

My previous C# mocking framework of choice was MOQ. It's very powerful and fairly easy to use, but I recently started using NSubstitute and fell in love with how easy and intuative it was to use.

The cleverest part is that unlike MOQ the mocks produced actually implement the interface they're mocking and this makes the code much clearer and a little bit shorter.

Here is a very simple example:

var mockThing = Substitute.For<IThing>();
mockThing.DoThingy().Returns("Something");

// Use mock thing
UseThing(mockThing);

In MOQ this is also quite straightforward but the setup code to change what a mocked method returns always had me reaching for Google.

var mockThing = new Mock<IThing>();
mockThing.Setup(m => m.Now()).Returns(new DateTime());

// Use mock thing
UseThing(mockThing.Object)

For a more complete comparison between Moq and NSubstutute you should read NSubstitute vs Moq. And, for a more detailed view of what NSubstitute can do you should read the getting started guide.

No Comments