使用 Moq 通过引用传递数组来验证方法

发布于 2024-08-28 17:00:06 字数 789 浏览 7 评论 0原文

给定以下接口,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゃ懵逼小萝莉 2024-09-04 17:00:06

为了验证 ref 参数,您需要将实际实例传递到验证调用中。这意味着您的第一个测试应如下所示:

[Test]
public void CanVerifyMethodsWithArrayRefParameter()
{
    var a = new Mock<ISomething>().Object;
    var strs = new string[0];
    a.DoManyRef(ref strs);
    Mock.Get(a).Verify(t => t.DoManyRef(ref strs));
}

问题的最后一句话使我相信您可能无法进行该更改,但这正是验证调用成功所需的。希望这有帮助。

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:

[Test]
public void CanVerifyMethodsWithArrayRefParameter()
{
    var a = new Mock<ISomething>().Object;
    var strs = new string[0];
    a.DoManyRef(ref strs);
    Mock.Get(a).Verify(t => t.DoManyRef(ref strs));
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文