by thorhalvor

Simple, succinct, pleasant to use

Going full TDD style or not, most developers I know have understood that we need Tests for our code, and when writing tests you need to substitute and isolate parts of code. Frameworks helping out with this, are for example Moles, Typemock, Moq, RhinoMock and NSubstitute. In this blogpost I will focus on the latter. If you interested in a comparison of these you can read Richard Banks blogpost.

NSubstitute’s goal is to be, as the title says, “Simple, succinct, pleasant to use”. And after using it in a project I have to say that it really is! What I find weird though, is that I haven’t heard more noise about it (positive noise: twitter, blogposts etc) until recently, because the guys behind NSubstitute has really done a good job. They don’t even argue about if it is called a mock, stub, test double, fake etc. Instead it is a substitute for something else. Simple!

We’ve attempted to make the most frequently required operations obvious and easy to use, keeping less usual scenarios discoverable and accessible, and all the while maintaining as much natural language as possible.

I woun’t show lots of examples here. If you are looking for that you can go to their Getting-Started pages. There you can see how the easily the mocks are created just by writing var repository = Substitute.For<IUserRepository>(); and how easily you can set up return values by writing repository.Login().Returns(true); They have cleaned up the plumbing code and by adding extensionmethods they have reduced the need for lamdas. Lamdas is good in many cases but they are not that readable in my opinion. And a test should be readable.

NSubstitute has also done a good job in the exceptionhandling when assertions are not met. The errormessage is clear and gives a detailed explanation of which and why an Assert did not return true.

NSubstitute is worth checking out. It’s easy downloadable through their NuGet pacakge. I don’t think I will change the mocking frameworks on projects I am already on but I think I will use it on minor projects until I get more comfortable with the more comprehensive tests.