NSubstitute:什么时候......不要在模拟无效方法时工作

NSubstitute: When....Do not working while mocking void method

我是 NSubtitute 的新手,很困惑为什么下面的测试用例会失败。

  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);
}

它适用于以下代码。唯一的区别是 class 中的方法回调(上例)和接口中的方法(下例)。

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);
} 

NSubstitute 旨在与接口一起使用。它对 类 有一些限制,比如只能为虚拟成员工作。

来自他们的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.