相关疑难解决方法(0)

NSubstitute-模拟任何参数的参数行为

我正在尝试IConfigurationProvider使用NSubstitute。我需要该方法bool TryGet(string key, out string value)返回不同键的值。所以像这样:

var configProvider = Substitute.For<IConfigurationProvider>();
configProvider.TryGet("key1", out Arg.Any<string>()).Returns(x => 
    { x[1] = "42"; return true; });
Run Code Online (Sandbox Code Playgroud)

但这无法编译。我需要一个模拟方法来实际将out参数设置为适当的值,而不管该参数是什么-它是一个依赖项,被测单元使用自己的参数调用此方法,而我只是希望它“返回”(如通过填充out参数返回)正确的键值。

这应该为该问题提供更多视角:

var value = "";
var configProvider = Substitute.For<IConfigurationProvider>();
configProvider
.TryGet("key1", out value)
.Returns(x => { 
    x[1] = "42"; 
    return true; 
});

var otherValue = "other";
configProvider.TryGet("key1", out value);
configProvider.TryGet("key1", out otherValue);

Assert.AreEqual("42", value);      // PASS.
Assert.AreEqual("42", otherValue); // FAIL.
Run Code Online (Sandbox Code Playgroud)

我需要两个断言都是正确的,因为该方法将由测试的类使用,并且可以自由传递它想要的任何out参数,我只需要用“ 42”填充即可。

c# unit-testing nsubstitute .net-core

7
推荐指数
2
解决办法
688
查看次数

标签 统计

.net-core ×1

c# ×1

nsubstitute ×1

unit-testing ×1