Unit tests are code written to test small pieces of functionality of big programs. Performing unit tests is always designed to be simple, A “UNIT” in this sense is the smallest component of the large code part that makes sense to test, mainly a method out of many methods of some class.

Unit tests take milliseconds, can be run at the press of a button, and don’t necessarily require any knowledge of the system at large. And when writing unit tests, you need to focus on the UNIT at hand and not consider other dependencies like services or variables. To accomplish that we need to use mocking. There are many Mocking frameworks out there, but today we will check NSubstitute.

To get started, first you need to add the NSubstitute package to your existing project, run the following

dotnet add package NSubstitute

Now let’s say that we have the following basic interface.

public interface IClaculator
{
    int Add(int x, int y);
}

This is a small test using XUnit and NSubstitute

using NSubstitute;
using Xunit;

public class CalculatorTests
{
    [Fact]
    public void Calculator_Add_Test()
    {
        ICalculator calculator = Substitute.For<ICalculator>();

        calculator.Add(1, 2).Returns(3);

        var result = calculator.Add(1, 2);
        Assert.Equal(3, result);
    }
}

let’s break it down. First, to create the mock object, we are using Substitute.For<T> and to tell our mock/substitute what it should return we are using the following syntax:

calculator.Add(1, 2).Returns(3);

here we are configuring the method Add, when it got 1 and 2 as parameters, it should return 3.

We can add more complex arguments and parameter substitutions like the following

Substitute for any argument
calculator.Add(Arg.Any<int>(), Arg.Any<int>()).Returns(10);
Substitute for any argument giving a condition
calculator.Add(Arg.Is<int>(x => x < 100), 1).Returns(10);
Returns any args
calculator.Add(1, 2).ReturnsForAnyArgs(100); // this will return 100 always.

Summary

NSubstitute is straightforward to create mocks/substitutes for your objects. There is more you can do with NSubstitute, you can learn more about it in the documentation or check the code here at github/nsubstitute