Month: August 2011

NSubstitute – Falling off a log easy mocking

Call me crazy, but I like my programming to be easy as pie. If it’s complicated or I have to jump through some hoops then something is decidedly wrong.

This is where NSubstitute comes in – it makes mocking dead easy, and the great thing is it integrates really well with Ninject for really easy unit testing with IoC. The NSubstitute home page has a great example of how the mocks work:

//Create:
var calculator = Substitute.For<ICalculator>();

//Set a return value:
calculator.Add(1, 2).Returns(3);
Assert.AreEqual(3, calculator.Add(1, 2));

//Check received calls:
calculator.Received().Add(1, Arg.Any<int>());
calculator.DidNotReceive().Add(2, 2);

//Raise events
calculator.PoweringUp += Raise.Event();

And when something goes wrong, it’s pretty succinct with the error messages:

CallNotReceivedException : Expected to receive call:
    Add(1, 2)
Actually received (non-matching arguments indicated with '*' characters):
    Add(*4*, *7*)
    Add(1, *5*)

Ahhh I do love a nice simple API with fluent support.

Posted by Dan in C#, Programming, 0 comments