Using the NSubstitute Library for Mocking

Learn how to mock dependencies using the NSubstitute library.

The NSubstitute library is a popular .NET mocking framework used for unit testing in C# and other .NET languages. Like other mocking frameworks, the NSubstitute library helps developers write unit tests that isolate the code under test and make it easier to verify the correctness of that code by controlling and inspecting interactions with its dependencies.

Compared to Moq, the NSubstitute library lacks some advanced features. However, it has its advantages, which include the following:

  • Lenient by default: The NSubstitute library uses a lenient mocking behavior by default, meaning that if we don’t explicitly set up expectations, the mock object doesn’t throw exceptions. This can make it more forgiving for scenarios where we’re primarily interested in mocking a few specific behaviors but don’t want to set up expectations for every method call.

  • No proxy generation: The NSubstitute library doesn’t generate proxy classes for the mocked objects, which can lead to improved performance in some cases. The Moq library, on the other hand, generates proxy classes, which may introduce a slight overhead.

  • Auto-mocking containers: The NSubstitute library provides an auto-mocking container feature that simplifies the process of creating mock objects and injecting them into the objects under test. This is handy for setting up complex test scenarios involving multiple dependencies.

  • Simplified property substitution: The NSubstitute library provides a simple method to substitute properties on objects, making it easy to control the behavior of property getters and setters during testing.

Get hands-on with 1400+ tech skills courses.