0

I am new to NSubtitute and really confused why below test case is failing.

  public class IFoo {
       public void SayHello(string to)
        {
          Console.writeLine("Method called");
        }
    }

[Test]
public void SayHello() {
    var counter = 0;
    var foo = Substitute.For<IFoo>();
    foo.When(x => x.SayHello("World"))
        .Do(x => counter++);

    foo.SayHello("World");
    foo.SayHello("World");
    Assert.AreEqual(2, counter);
}

And it works for below code. Only difference is callback on method in class(Above case) and method in Interface(Below case).

public interface IFoo {
    void SayHello(string to);
}

[Test]
public void SayHello() {
    var counter = 0;
    var foo = Substitute.For<IFoo>();
    foo.When(x => x.SayHello("World"))
        .Do(x => counter++);

    foo.SayHello("World");
    foo.SayHello("World");
    Assert.AreEqual(2, counter);
} 
user3640709
  • 83
  • 1
  • 9

1 Answers1

4

NSubstitute is intended to be used with interfaces. It has some limitations with classes like only being able to work for virtual members.

From their documentation:

Warning: Substituting for classes can have some nasty side-effects. For starters, NSubstitute can only work with virtual members of the class, so any non-virtual code in the class will actually execute! If you try to substitute for your class that formats your hard drive in the constructor or in a non-virtual property setter then you’re asking for trouble. If possible, stick to substituting interfaces.