gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:27:51 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com