Skip to content

Instantly share code, notes, and snippets.

@robdmoore
Last active December 11, 2015 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robdmoore/4618493 to your computer and use it in GitHub Desktop.
Save robdmoore/4618493 to your computer and use it in GitHub Desktop.
Understanding the impact of NSubstitute's .Returns() static stack implementation
using System;
using NSubstitute;
using NSubstitute.Exceptions;
using NUnit.Framework;
namespace Tests
{
public class Class1
{
public interface Interface
{
int Method();
}
[Test]
[ExpectedException(typeof(CouldNotSetReturnException))]
public void Test1()
{
var x = Substitute.For<Interface>();
0.Returns(3);
// No calls on the stack so we can't set up a return value
}
[Test]
public void Test2()
{
var x = Substitute.For<Interface>();
var y = Substitute.For<Interface>();
y.Method().Returns(5);
// Pushes y.Method() call to the stack
// .Returns pops the y.Method() call off the stack
x.Method().Returns(y.Method() + 1);
// Pushes x.Method() call to the stack
// Pushes y.Method() call to the stack
// .Returns pops the last item off the stack (the y.Method() call)
Assert.That(x.Method(), Is.EqualTo(0));
Assert.That(y.Method(), Is.EqualTo(6));
}
[Test]
public void Test3()
{
var x = Substitute.For<Interface>();
x.Method();
// Push onto stack
1.Returns(3);
// Pop off stack
Assert.That(x.Method(), Is.EqualTo(3));
}
[Test]
public void Test4()
{
var x = Substitute.For<Interface>();
x.Method();
// Push onto stack
"".Returns("");
// Pop off stack - it doesn't inspect the type; it's just a pure stack
Assert.Throws<InvalidCastException>(() => x.Method());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment