nsubstitute/NSubstitute — pull request #151 by Shaedar (2014-05-13 19:08:07+00:00)
Title: Implemented and tested ReturnForFirst extension for Returns.

I added a method called ReturnForFirst. It works similar to Returns, but it only takes one parameter. So it returns that parameter when the substitute is called the first time and returns null for every call after the first. I think Returns should already work like this, but I thought it might be easier or make more sense to add another method for it.

Why?

Because now when you want a substitute to return X for any arg that is a string for example, it will do it for ALL the calls for that method in the substitute. This means that in the actual production code we can call a dependency 10 times with any string what-so-ever and it will always return X. When in reality you would want your test to fail if there are multiple calls to the method of the substituted dependency.

[Test]
public void Test()
{
substitute.DoStuff(Arg.Any()).Returns("YOLO");

var result = ProductionCode();

Assert.That(result, Is.EqualTo("YOLO"));
}

public string ProductionCode()
{
dependency.DoStuff("Moo");
dependency.DoStuff("Rawr");
return dependency.DoStuff("Mew-hah");
}

So in this test we want to check that the production code method returns the value it gets from a dependency. The test will pass. But the production code is far from perfect. You could do the same thing that ReturnForFirst("YOLO") does by doing Returns("YOLO", null); but I think that is a more messy syntax.

That's all I had in mind! Thanks for listening.