Welcome to NSubstitute
Mock, stub, fake, spy, test double? Strict or loose? Nah, just substitute for the type you need!
NSubstitute is designed for Arrange-Act-Assert (AAA) testing, so you just need to arrange how it should work, then assert it received the calls you expected once you're done.
-
Install via NuGet:
Install-Package NSubstitute - Optional analysers for C#:
Install-Package NSubstitute.Analyzers. CSharp - Optional analysers for VB:
Install-Package NSubstitute.Analyzers. VisualBasic - Source
Simple, succinct, pleasant to use
//Create:
var calculator = Substitute.For<ICalculator>();
//Set a return value:
calculator.Add(1, 2).Returns(3);
Assert.AreEqual(3, calculator.Add(1, 2));
//Check received calls:
calculator.Received().Add(1, Arg.Any<int>());
calculator.DidNotReceive().Add(2, 2);
//Raise events
calculator.PoweringUp += Raise.Event();
Helpful exceptions
ReceivedCallsException : Expected to receive a call matching:
Add(1, 2)
Actually received no matching calls.
Received 2 non-matching calls (non-matching arguments indicated with '*' characters):
Add(*4*, *7*)
Add(1, *5*)
Another library?
There are already some great mocking libraries around for .NET, so why create another? We found that for all their great features, none of the existing libraries had the succinct syntax we were craving — the code required to configure test doubles quickly obscured the intention behind our tests.
We've attempted to make the most frequently required operations obvious and easy to use, keeping less usual scenarios discoverable and accessible, and all the while maintaining as much natural language as possible.
Perfect for those new to testing, and for others who would just like to to get their tests written with less noise and fewer lambdas.