Skip to content

Instantly share code, notes, and snippets.

@gabrieljoelc
Forked from robdmoore/gist:4618493
Last active December 13, 2015 22:59
Show Gist options
  • Save gabrieljoelc/4988180 to your computer and use it in GitHub Desktop.
Save gabrieljoelc/4988180 to your computer and use it in GitHub Desktop.
Tests1-4 are NSubstitute static stack demonstrations by @robdmoore. I added Tests5-6 to demonstrate a class substitution gotcha that happens if the Object#Equals() is overriden in a class used for an method argument match.
using System;
using NSubstitute;
using NSubstitute.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class Class1
{
public interface Interface
{
int Method();
}
[TestMethod]
[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
}
[TestMethod]
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.AreEqual(0, x.Method());
Assert.AreEqual(6, y.Method());
}
[TestMethod]
public void Test3()
{
var x = Substitute.For<Interface>();
x.Method();
// Push onto stack
1.Returns(3);
// Pop off stack
Assert.AreEqual(3, x.Method());
}
[TestMethod]
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
}
public class Foo
{
public virtual bool Method(Bar bar)
{
return bar != null;
}
}
public class Bar
{
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
[TestMethod]
public void Test5()
{
var x = Substitute.For<Foo>();
var y = Substitute.For<Bar>();
// because Bar#Equals() is overriden, y will not match
x.Method(y).Returns(true);
Assert.IsFalse(x.Method(y));
}
[TestMethod]
public void Test6()
{
var x = Substitute.For<Foo>();
var y = Substitute.For<Bar>();
// have to have to use Object.ReferenceEquals() to get a arguement match for y
x.Method(Arg.Is<Bar>(bar => ReferenceEquals(bar, y))).Returns(true);
Assert.IsTrue(x.Method(y));
}
}
}
@gabrieljoelc
Copy link
Author

It looks like there's a closed issue with some commits to fix the gotcha in Tests5-6: nsubstitute/NSubstitute#77. So this gotcha seems to only apply to the version of NSub that we are using (1.4.3).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment