使用 Moq 通过引用传递数组来验证方法
给定以下接口,
public interface ISomething {
void DoMany(string[] strs);
void DoManyRef(ref string[] strs);
}
我想验证是否调用了 DoManyRef 方法,并将任何字符串数组作为 strs
参数传递。以下测试失败:
public void CanVerifyMethodsWithArrayRefParameter() {
var a = new Mock<ISomething>().Object;
var strs = new string[0];
a.DoManyRef(ref strs);
var other = It.IsAny<string[]>();
Mock.Get(a).Verify(t => t.DoManyRef(ref other));
}
虽然以下测试不需要通过引用传递数组:
public void CanVerifyMethodsWithArrayParameter() {
var a = new Mock<ISomething>().Object;
a.DoMany(new[] { "a", "b" });
Mock.Get(a).Verify(t => t.DoMany(It.IsAny<string[]>()));
}
我无法更改接口以消除通过引用的要求。
Given the following interface
public interface ISomething {
void DoMany(string[] strs);
void DoManyRef(ref string[] strs);
}
I would like to verify that the DoManyRef method is called, and passed any string array as the strs
parameter. The following test fails:
public void CanVerifyMethodsWithArrayRefParameter() {
var a = new Mock<ISomething>().Object;
var strs = new string[0];
a.DoManyRef(ref strs);
var other = It.IsAny<string[]>();
Mock.Get(a).Verify(t => t.DoManyRef(ref other));
}
While the following not requiring the array passed by reference passes:
public void CanVerifyMethodsWithArrayParameter() {
var a = new Mock<ISomething>().Object;
a.DoMany(new[] { "a", "b" });
Mock.Get(a).Verify(t => t.DoMany(It.IsAny<string[]>()));
}
I am not able to change the interface to eliminate the by reference requirement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了验证 ref 参数,您需要将实际实例传递到验证调用中。这意味着您的第一个测试应如下所示:
问题的最后一句话使我相信您可能无法进行该更改,但这正是验证调用成功所需的。希望这有帮助。
For verifying against ref arguments, you need to pass the actual instance into the verify call. This means your first test should appear as follows:
The final sentence of the question leads me to believe you might not be able to make that change, but that is what is required for the Verify call to succeed. Hope this helps.