简体   繁体   English

NSubstitute在循环中多次调用时返回意外值

[英]NSubstitute returning unexpected values when called multiple times in a loop

I have come across is situation when mocking a method with an output parameter using NSubstitute. 我遇到过使用NSubstitute模拟带输出参数的方法的情况。 I'm not sure how best to explain it in text, so I'll use some contrived examples and test cases... 我不确定如何最好地在文本中解释它,所以我将使用一些人为的例子和测试用例......

In this contrived example, I'll be using a NSubstitute mock of a IDictionary<string, string> . 在这个人为的例子中,我将使用一个IDictionary<string, string>的NSubstitute mock。

private static IDictionary<string, string> GetSubstituteDictionary()
{
    IDictionary<string, string> dict = Substitute.For<IDictionary<string, string>>();

    string s;
    dict.TryGetValue("key", out s).Returns(ci => { ci[1] = "value"; return true; });

    return dict;
}

Now, when I use this mock object in a simple manner, it returns as expected: 现在,当我以简单的方式使用这个模拟对象时,它会按预期返回:

[Test]
public void ExampleOne()
{
    var dict = GetSubstituteDictionary();

    string value;
    bool result = dict.TryGetValue("key", out value);

    Assert.That(result, Is.True); // this assert passes.
    Assert.That(value, Is.EqualTo("value")); // this assert passes.
}

However, when I call the same code in a for loop, I get some unexpected behaviour: 但是,当我在for循环中调用相同的代码时,我会遇到一些意外的行为:

[Test]
public void ExampleTwo()
{
    var dict = GetSubstituteDictionary();

    for (int i = 0; i < 2; i++)
    {
        string value;
        bool result = dict.TryGetValue("key", out value);

        Assert.That(result, Is.True); // this assert FAILS - unexpected!
        Assert.That(value, Is.EqualTo("value")); // this assert still passes.
    }
}

In particular, the Assert.That(result, Is.True); 特别是, Assert.That(result, Is.True); assertion passes on the first iteration of the loop, but fails on the second (and any subsequent) iteration. 断言在循环的第一次迭代中传递,但在第二次(以及任何后续)迭代时失败。

However, if I modify the string value; 但是,如果我修改string value; line to be string value = null; line to be string value = null; , the assertion passes for all iterations. ,断言遍历所有迭代。

What is causing this anomaly? 造成这种异常的原因是什么? Is this due to some semantics of C# for loops that I am missing, or is it an issue with the NSubstitute library? 这是由于我缺少的C#for循环的一些语义,还是NSubstitute库的问题?

The reason is that the value variable changes in the loop (set via the output parameter), so that it no longer matches the call you stubbed out. 原因是value变量在循环中更改(通过输出参数设置),因此它不再与您删除的调用匹配。

You can try using .ReturnsForAnyArgs() , although you'll need to check the key within the stub then rather than via an argument matcher. 您可以尝试使用.ReturnsForAnyArgs() ,尽管您需要检查存根中的键,而不是通过参数匹配器。

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

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