DEV Community

Hassan BOLAJRAF
Hassan BOLAJRAF

Posted on

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

Note
You can check other posts on my personal website: https://hbolajraf.net

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:

Install-Package NSubstitute
Enter fullscreen mode Exit fullscreen mode

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:

public interface IDataRepository
{
    string GetData();
}
Enter fullscreen mode Exit fullscreen mode

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:

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

mockRepository.GetData(Arg.Any<int>()).Returns("Mocked Data");
Enter fullscreen mode Exit fullscreen mode

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:

mockRepository.Received().GetData();
mockRepository.Received(3).GetData(); // Verifies that GetData was called exactly 3 times.
Enter fullscreen mode Exit fullscreen mode

Configuring Callbacks

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

mockRepository.GetData().Returns(x => "Mocked Data");
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)