从接收到的调用中提取参数并对其进行断言

Extracting arguments from received call and assert on them

如何对接收到的调用的参数进行断言?下面的示例不起作用,因为传递给 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..DoArg.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>>>());