如何从收到的呼叫中对参数进行断言?下面的示例不起作用,因为从未调用传递给Arg.Do()的操作.
IEnumerable<Tuple<string, string>> receivedlArgs = null;
provider.Received(1)
.SetValuesAsync(Arg.Do<IEnumerable<KeyValuePair<string,object>>>(
args =>
{
receivedlArgs = args.Select(a => new Tuple<string, string>(a.Key, a.Value.ToString()));
}));
// assert (using FluentAssertions - but just for the example)
receivedlArgs.Should().Equal(Tuple.Create("Key1", "foo"), Tuple.Create("Key2", "bar"));
解决方法:
标准方法是使用已收到的正确参数来声明调用,而不是捕获参数并对其进行声明.
provider.Received(1)
.SetValuesAsync(Arg.Is<IEnumerable<KeyValuePair<string,object>>>(
pairs => SameElements(pairs, new [] { Tuple.Create("Key1", "foo"), ... })));
您可以将这些代码或多或少地提取到不同的方法中,以使其更具可读性.
这种方法的问题在于,它没有像FluentAssertions这样的东西提供太多关于参数之间差异的信息.在这种情况下,我们可以退回到When..Do或Arg.Do来根据您的问题捕获参数.在那些情况下,我们不想使用Received,只要将调用存根以执行特定的操作即可.还要确保在调用要测试的方法之前设置Do回调.
//Arrange
IEnumerable<KeyValuePair<string, object>> receivedArgs = null;
provider.SetValuesAsync(
Arg.Do<IEnumerable<KeyValuePair<string,object>>>(x => receivedArgs = x)
);
// Act:
callWeAreTesting();
// Assert:
receivedArgs.Should()....
或者我们可以使用When..Do语法:
provider.WhenForAnyArgs(x => x.SetValuesAsync(null))
.Do(x => receivedArgs = x.Args<IEnumerable<KeyValuePair<string,object>>>());