NSubstitute is a friendly substitute for .NET mocking frameworks.
It's like a stub with property behaviour.
With nice semantics for setting return values.
It only has one mode - loose semantics, which you can query afterwards.
It's meant to be simple, succinct and pleasant to use.
It also isn't released yet, but you can grab the source from GitHub if you'd like to try it out.
Let's say we have a basic calculator interface:
public interface ICalculator
{
void SwitchOn();
int Add(int a, int b);
int Subtract(int a, int b);
string Name { get; set; }
DateTime Now { get; }
string Firmware { set; }
}
We can ask NSubstitute to create a substitute instance for this type (you could call it a stub, mock, or fake, but why bother when we just want to substitute in an instance we have some control over?).
[Test]
public void Use_a_shiny_new_substitute()
{
var calculator = Substitute.For();
calculator.SwitchOn();
Assert.That(calculator.Add(1,2), Is.EqualTo(default(int)));
}
Now we can tell our substitute to return different values for different calls:
[Test]
public void Return_different_values_for_different_arguments()
{
var calculator = Substitute.For();
calculator.Add(1, 2).Returns(3);
calculator.Add(20, 30).Returns(50);
Assert.That(calculator.Add(20, 30), Is.EqualTo(50));
Assert.That(calculator.Add(1, 2), Is.EqualTo(3));
}
And we can check that our substitute received a call:
[Test]
public void Check_a_call_was_received()
{
var calculator = Substitute.For();
calculator.Add(1, 2);
calculator.Received().Add(1, 2);
}
The .NET space is already well populated with mocking frameworks. Why create another? We found that none of the existing frameworks were succinct enough and the code written to use one of these frameworks quickly turns C# in to PERL.
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 dipping their toe into the testing space, or for others who would just like to use less lambdas.
NSubstitute.MakesProgramming(Easier).Returns(true);
For more information, have a look at the NSubstitute project on GitHub.