Post

C# | Using NSubstitute NuGet Package for C# Unit Tests

NSubstitute is a powerful mocking library for C# unit tests, allowing developers to easily create substitute objects (mocks) for dependencies. These substitutes can be configured to behave in specific ways, making them ideal for isolating the unit under test and verifying its interactions with dependencies. In this guide, we’ll explore how to use NSubstitute in your C# unit tests with detailed examples.

Installation

Before you can start using NSubstitute, you need to install the NSubstitute NuGet package in your C# project. You can do this via the NuGet Package Manager Console or through the Visual Studio UI:

1
Install-Package NSubstitute

Alternatively, you can search for “NSubstitute” in the NuGet Package Manager UI and install it from there.

Basic Usage

Let’s start with a basic example of using NSubstitute to mock an interface. Suppose we have the following interface representing a data repository:

1
2
3
4
public interface IDataRepository
{
    string GetData();
}

Now, let’s create a unit test for a class (DataProcessor) that depends on this interface. We’ll use NSubstitute to mock the IDataRepository interface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using NSubstitute;
using Xunit;

public class DataProcessorTests
{
    [Fact]
    public void ProcessData_WhenDataIsAvailable_ReturnsProcessedData()
    {
        // Arrange
        var mockRepository = Substitute.For<IDataRepository>();
        mockRepository.GetData().Returns("Mocked Data");
        var dataProcessor = new DataProcessor(mockRepository);

        // Act
        var result = dataProcessor.ProcessData();

        // Assert
        Assert.Equal("Processed Mocked Data", result);
    }
}

In this example:

  • We create a substitute for the IDataRepository interface using Substitute.For<IDataRepository>().
  • We configure the substitute’s behavior using the Returns method to return “Mocked Data” when the GetData method is called.
  • We then create an instance of DataProcessor, passing the mock repository as a dependency.
  • Finally, we invoke the method under test (ProcessData) and verify its behavior.

Advanced Usage

NSubstitute provides various advanced features, such as argument matching, configuring return values based on arguments, and verifying method calls. Let’s look at some examples:

Argument Matching

You can use argument matching to specify different behaviors based on method arguments. For example:

1
mockRepository.GetData(Arg.Any<int>()).Returns("Mocked Data");

This configuration will return “Mocked Data” regardless of the integer argument passed to GetData.

Verifying Method Calls

You can verify that specific methods were called on the substitute and optionally specify the number of times they were called. For example:

1
2
mockRepository.Received().GetData();
mockRepository.Received(3).GetData(); // Verifies that GetData was called exactly 3 times.

Configuring Callbacks

You can configure substitutes to perform custom actions when methods are called. For example:

1
mockRepository.GetData().Returns(x => "Mocked Data");

This configuration uses a lambda expression to return “Mocked Data” based on the arguments passed to GetData.

What Next?

NSubstitute is a powerful mocking library that simplifies unit testing in C#. By allowing developers to create substitutes for dependencies with specific behaviors, NSubstitute enables more effective isolation of units under test and verification of their interactions. With its intuitive syntax and advanced features, NSubstitute is a valuable tool for writing robust and maintainable unit tests in C#.

For more information on NSubstitute, refer to the official documentation.

This post is licensed under CC BY 4.0 by the author.