【问题标题】:Moq - Updating Reference Parameter Inside Callback Not WorkingMoq - 更新回调内部的参考参数不起作用
【发布时间】:2021-02-05 14:22:15
【问题描述】:

我正在尝试对循环调用函数的方法进行单元测试。提供给该方法的参数之一是 List<string>,在循环外声明,应在每次调用时更新它传递给它。

我一直在尝试使用我在 SO 上找到的一些示例来模拟这种行为,这些示例涉及更新 Callback() 内部的参数,但这并没有像预期的那样对我有用。

这是我遇到的问题的一个简短示例:

方法

public async Task DoSomething() {
    var strings = new List<string>();

    for(i = 0; i < 2; i++) {
        var response = await _responder.GetResponse(i, strings);
        //method adds a new string into the collection on each call
    }
}

所以为了测试这一点,我需要模拟两个方法调用,知道字符串集合在一个为空而在另一个包含一个元素...

测试

public async Task TestDoSomething() {
    var strings = new List<string>();

    var mock = new Mock<Responder>();
    mock.Setup(x => x.GetResponse(0, strings)) //mocks first iteration of loop
        .ReturnsAsync(new Response())
        .Callback<int, List<string>>((number, stringCollection) => {
            stringCollection = new List<string> {"addedString"}; //this is where the problem occurs
            strings = stringCollection;
        });

    mock.Setup(x => x.GetResponse(1, strings)) //mocks second iteration of loop
        .ReturnsAsync(new Response());

    //...
}

因此,当我尝试更新回调中的字符串集合时,工作室会突出显示该参数并给我警告The value passed to the method is never used because it is overwritten in the method body before being read

测试失败,因为设置不匹配,尝试调试会导致测试崩溃并退出。

任何人都可以在这里指出正确的方向吗?在警告消息和这些东西的所有其他示例仅使用 Returns 而不是 ReturnsAsync 的事实之间,我猜这与更新参数的时间有关。

提前致谢!

【问题讨论】:

    标签: c# unit-testing callback moq


    【解决方案1】:

    不确定您要测试方法调用的确切内容或添加到集合中的值。 但是如果你想测试那个方法被调用了,你可以像这样使用验证函数 -

    mock.Verify(mock => mock.GetResponse(It.IsAny<int>(), strings), Times.Exactly(2));
    

    PS。你应该使用It.IsAny&lt;int&gt;(),因为第一个参数从循环中获取索引所以_responder.GetResponse(0, strings)只调用一次等等。

    【讨论】:

    • 谢谢你 - 我更希望测试在一次调用中添加到集合中的值是否会出现在下一次调用的集合中。如果不是这样,那么您在此处概述的方法就是我会采用的方法!
    猜你喜欢
    • 1970-01-01
    • 2010-10-18
    • 2015-09-12
    • 2013-05-09
    • 1970-01-01
    • 2017-12-30
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多