【问题标题】:NSusbtitute incorrectly calculates the number of calls on a mockNSusbtitute 错误地计算了模拟的调用次数
【发布时间】:2017-04-26 10:19:08
【问题描述】:
public class Device
{
    private readonly IProtocol _protocol;

    public Device(IProtocol protocol)
    {
        _protocol = protocol;
    }

    public bool Connect(string port)
    {
        for (int i = 0; i < 3; i++)
        {
            if (_protocol.Connect(port))
                return true;
        }
        return false;
    }
}
public interface IProtocol
{
     bool Connect(string port);
}

    [Test]
    public void Connect_FailedThrice_ThreeTries()
    {
        IProtocol provider = Substitute.For<IProtocol>();
        provider.Connect(Arg.Any<string>()).Returns(false);

        var sut = new Device(provider);
        sut.Connect(Arg.Any<string>());

        provider.Received(3).Connect(Arg.Any<string>());
    }

运行单元测试的结果 - 错误提示 Connect 方法被调用了两次,而不是三次。调试显示该方法被调用了三次。

【问题讨论】:

    标签: c# unit-testing mocking nsubstitute


    【解决方案1】:

    NSubstitute documentation

    在不调用 .Returns 或 Received() 的情况下使用 Arg.Is 或 Arg.Any 可能会导致您的测试以意想不到的方式运行。有关详细信息,请参阅如何不使用参数匹配器。

    尝试传入sut.Connect方法任意字符串

    [TestMethod]
    public void Connect_FailedThrice_ThreeTries()
    {
         IProtocol provider = Substitute.For<IProtocol>();
         provider.Connect(Arg.Any<string>()).Returns(false);
    
         var sut = new Device(provider);
         sut.Connect("hello");
    
         provider.Received(3).Connect(Arg.Any<string>());
    }
    

    【讨论】:

    • 它有效。谢谢你。嗯......从 NSubstitute 的 API 角度来看,这似乎非常不一致。这种行为远非显而易见。
    • @EngineerSpock 好的,我发现了 :)
    猜你喜欢
    • 1970-01-01
    • 2022-08-02
    • 2020-05-07
    • 2023-03-04
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多