NSubstitute creates mock objects for .NET tests with Arrange-Act-Assert flows. It targets interfaces and virtual members with concise syntax.
Overview
NSubstitute is a .NET library for creating test substitutes—mocks, stubs, or spies—without heavy ceremony. It is built around Arrange-Act-Assert testing: configure return values and behavior, exercise code under test, then assert which calls occurred.
You create a substitute with Substitute.For, set returns on methods and properties, verify Received and DidNotReceive call patterns, match arguments flexibly, chain multiple return values, and raise events on substitutes. The design favors readable, natural-language-style configuration over verbose lambda setup.
The library works with interfaces and classes that expose virtual members; non-virtual class members cannot be substituted reliably. Optional Roslyn analysers help catch common mistakes during development. Install is via NuGet, with separate analyser packages for C# and Visual Basic.
The authors position it for newcomers to testing and for teams that want less noise in test code compared with older mocking APIs. Help is available through project issues and Stack Overflow’s nsubstitute tag.
Key features
- Substitute.For test double creation
- Returns configuration for methods and properties
- Received and DidNotReceive assertions
- Argument matching for calls
- Sequences of return values
- Event raising on substitutes
- Optional Roslyn analyser packages
- NuGet distribution
Use cases
- Unit test services with mocked dependencies
- Verify interaction patterns after actions
- Stub external APIs in .NET tests
- Keep AAA tests readable