开发者

Verifying method with array passed by reference using Moq

开发者 https://www.devze.com 2022-12-26 06:00 出处:网络
Given the following interface public interface ISomething { void DoMany(string[] strs); void DoManyRef(ref string[] strs);

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开发者_JAVA技巧.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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消