c# - 如何使 Moq 忽略 ref 或 out 的参数

标签 c# moq

在 RhinoMocks 中,您可以将模拟作为一揽子声明告知 IgnoreArguments。在 Moq 中,您似乎必须为每个参数指定 It.IsAny()。但是,这不适用于 ref 和 out 参数。如何在需要最小化内部服务调用以返回特定结果的地方测试以下方法:

public void MyMethod() {
    // DoStuff

    IList<SomeObject> errors = new List<SomeObject>();
    var result = _service.DoSomething(ref errors, ref param1, param2);

    // Do more stuff
}

测试方法:

public void TestOfMyMethod() {
    // Setup
    var moqService = new Mock<IMyService>();
    IList<String> errors;
    var model = new MyModel();

    // This returns null, presumably becuase "errors" 
    // here does not refer to the same object as "errors" in MyMethod
    moqService.Setup(t => t.DoSomething(ref errors, ref model, It.IsAny<SomeType>()).
        Returns(new OtherType()));  
}

更新:因此,将错误从“ref”更改为“out”是可行的。所以看起来真正的问题是有一个你不能注入(inject)的 ref 参数。

最佳答案

正如您已经发现问题出在您的 ref 参数上。

Moq 当前仅支持对 ref 参数进行精确匹配,这意味着调用仅在您传递与您在 Setup 中使用的相同实例时匹配。所以没有通用匹配,所以 It.IsAny() 将不起作用。

见最小起订量 quickstart

// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);

最小起订量discussion group :

Ref matching means that the setup is matched only if the method is called with that same instance. It.IsAny returns null, so probably not what you're looking for.

Use the same instance in the setup as the one in the actual call, and the setup will match.

关于c# - 如何使 Moq 忽略 ref 或 out 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889810/

相关文章:

c# - DllImport 在 Docker 上不起作用 - DllNotFoundException

unit-testing - 如何设置对特定类型的 Equals 调用覆盖 MoQ 中的 Equals?

c# - NuGet 包将非托管 dll 复制到根目录而不是 bin

c# - 如何模拟未声明为虚拟的外部类中的方法

c# - 我可以模拟私有(private)方法吗?或者测试此 POST 方法的正确方法是什么?

linq - 定制匹配最小起订量

c# - 如何重构静态方法以便测试我的方法?

c# - Azure 指标从 MetricsClient 返回 0

c# - 为什么 Extender Provider Properties 在 C# 窗口应用程序中的 Designer 中丢失?

c# - 读取多个 XML 属性