For most developers, coding tests is one of most challenging and boring tasks you do during your development, but trust me, it is a necessary evil and everybody will thank when you deliver a tested and reliable code.
One of the most time consuming task is to mockup dependencies your class depends on. Some classes can have so many dependencies, you will have to write all return conditions. Also you´ll need to instantiate all of them before you test your class.
I’m assuming you follow the DI (Dependency Injection) pattern principles in your code.
When you use dependencies mockups, you need to tell all return scenarios your class need to coverage all paths of your custom code. NSubstitute comes in help to easily create those mockup dependency classes.
The main method of NSubstitute library is Substitute.For<T>(), where T can be a class or interface you want to mock. After that, you can inject the returns values to your T mock class methods as you need.
NSubstitute is available as package in nuget.org package manager. See how to use it:
Let’s assume you have an ICalculator interface class. This interface has 4 Methods Add(), Subtract(), Multiply() and Divide() as follow:
In your custom class you declare the ICalculator interface in the class constructor method and create a method to do all calculations and return the sum of all values:
To test your CustomClass, create a unit test class (I’m using Nunit) and write the assertions to your class, in this case 2 valid scenarios and 1 invalid:
If you look to code above, the CustomClass class needs the ICalculator interface implementation to do all execution inside the DoCalculations() method. NSubstitute comes in this part, creating a concrete class for your interface. To use it, create a method in your test class, returning the ICalculator interface:
The Substitute.For<T>() method will create a fake concrete class of ICalculator interface and will expose all interface methods to be configured. You can add to each method call parameter condition, a return value accordingly the return value of interface method.
And finally, change the CustomClass constructor method in your test class to add the CreateMock() method.
Voilá, now test your class, and the ICalculator interface will return for all condition parameters, the return values you’ve configured in the mock method. If a condition doesn’t match a return value you’ve configured, a default value will return (null for reference types, default for value types).
For a complete NSubstitute documentation, click this link. With NSubstitute you’ll have a set of tools to easily create your dependencies mockup class (You can also reuse your mockup classes across projects). This will help you to gain productivity in your development.