问题描述
我试图模拟一个没有参数的方法,并在单元测试中多次调用它。 这是我的主要代码:
foreach (Device device in deviceList)
{
ResponseCode response = this.client.GetState(device.Name,out State state);
DeviceStatus deviceStatus = new DeviceStatus
{
Device = device,ResponseCode = response,State = state
}
}
以下是我在测试中所做的:
IClient mockClient;
var deviceList = new List<Device>
{
new Device { Name = "device1" },new Device { Name = "device2" },new Device { Name = "device3" }
}
this.mockClient.GetState(Arg.Is<string>(x => x == "device1"),out State device1State).
Returns(x =>
{
x[1] = preSetStateForDevice1;
return ResponseCode.Success;
});
this.mockClient.GetState(Arg.Is<string>(x => x == "device2"),out State device2State).
Returns(x =>
{
x[1] = preSetStateForDevice2;
return ResponseCode.Success;
});
this.mockClient.GetState(Arg.Is<string>(x => x == "device3"),out State device3State).
Returns(x =>
{
x[1] = preSetStateForDevice3;
return ResponseCode.Success;
});
在调试中,我发现 GetState 的三个调用都返回与第一个调用相同的结果。 我知道有没有out参数的多次返回的帖子或没有out参数的单一方法调用,但我不知道如何使这种多次调用没有out参数的方法有效,请帮忙。谢谢!
更新:我也尝试通过调用序列而不是输入值来设置和返回,如下所示:
this.mockClient.GetState(Arg.Any<string>(),out State state).
Returns(x =>
{
x[1] = preSetStateForDevice1;
return ResponseCode.Success;
},x =>
{
x[1] = preSetStateForDevice2;
return ResponseCode.Success;
},x =>
{
x[1] = preSetStateForDevice3;
return ResponseCode.Success;
});
它也没有用
更新:从这篇文章找到了一个方法:NSubstitute,out Parameters and conditional Returns 在第二个 try 方法中使用 ReturnsForAnyArgs 而不是 Returns 将起作用。不知道为什么...
解决方法
参数匹配对于 out
和 ref
参数可能有点棘手,因为最初指定调用时使用的值会在测试执行期间发生变化。
解决此问题的最可靠方法是使用 Arg.Any
to match the out
argument。例如:
mockClient
.GetState(Arg.Is<string>(x => x == "device1"),out Arg.Any<State>())
.Returns(...)
有关此问题的原因的详细信息,请参阅 Setting out
and ref
arguments: Matching after assignments。