简体   繁体   English

NSubstitute:何时…在模拟void方法时不工作

[英]NSubstitute: When…Do not working while mocking void method

I am new to NSubtitute and really confused why below test case is failing. 我是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);
}

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

NSubstitute is intended to be used with interfaces. NSubstitute旨在与接口一起使用。 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! 对于初学者来说,NSubstitute只能与该类的虚拟成员一起使用,因此该类中的任何非虚拟代码都将实际执行! 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. 如果可能,请坚持替换接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM