问题描述
我正在尝试使用 NSubstitute 模拟 IConfigurationProvider
.我需要方法 bool TryGet(string key, out string value)
来返回不同键的值.所以是这样的:
I'm trying to mock IConfigurationProvider
with NSubstitute. I need the method bool TryGet(string key, out string value)
to return values for differing keys. So something like this:
var configProvider = Substitute.For<IConfigurationProvider>();
configProvider.TryGet("key1", out Arg.Any<string>()).Returns(x =>
{ x[1] = "42"; return true; });
但这不能编译.我需要模拟方法将 out 参数实际设置为适当的值,无论该参数是什么 - 它是一个依赖项,被测单元使用自己的参数调用此方法,我只希望它返回"(如通过填写 out 参数返回)正确的键值.
but this does not compile.I need the mocked method to actually set the out parameter to the appropriate value, regardless of what that parameter is - it's a dependency, the unit under test calls this method with its own parameters and I just want it to "return" (as in return by filling the out parameter) correct values for keys.
这应该可以让您更深入地了解问题:
This should give more perspective on the problem:
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.
我需要两个断言都为真,因为这个方法将被测试类使用,并且可以自由地传递它想要的任何输出参数,我只需要用42"填充它.
I need both assertions to be true, since this method will be used by the tested class and it's free to pass any out parameter it wants, I just need to fill it with "42".
推荐答案
configProvider.TryGet("key1", out Arg.Any())
不是有效的 C# 语法,它是为什么它不会编译.
configProvider.TryGet("key1", out Arg.Any<string>())
is not valid C# syntax, which is why it wont compile.
您需要为 out 参数使用实际变量.
You need to use an actual variable for the out parameter.
以下在测试时有效.
//Arrange
var expectedResult = true;
var expectedOut = "42";
var actualOut = "other";
var anyStringArg = Arg.Any<string>();
var key = "key1";
var configProvider = Substitute.For<IConfigurationProvider>();
configProvider
.TryGet(key, out anyStringArg)
.Returns(x => {
x[1] = expectedOut;
return expectedResult;
});
//Act
var actualResult = configProvider.TryGet(key, out actualOut);
//Assert
Assert.AreEqual(expectedOut, actualOut); // PASS.
Assert.AreEqual(expectedResult, actualResult); // PASS.
这篇关于NSubstitute - 模拟任何参数的参数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!