Moq:如何确保Verify()报告不匹配的参数

时间:2016-02-11 16:44:16

标签: moq

我使用Moq进行了以下单元测试验证:

var mock = new Mock<IDoSomethingUseful>();

var sut = new Thingy(mock.Object);
sut.CallDoSomethingUseful();

mock.Verify(
    somethingUseful => somethingUseful.Move(
        It.Is<MyVector>( 
            myVector => myVector.x == 123)), Times.Once, "This fail message needs to be hard-coded with myVector.x was not equal to 123");
  • 如何让Verify()告诉我谓词匹配失败?测试运行器仅报告调用失败,因此我需要依赖硬编码的消息。

1 个答案:

答案 0 :(得分:0)

使用Callback可以访问调用参数。请参阅回调 here部分。

在您的情况下,您可以为测试添加{em>期望值x,并在Callback中获取实际值。最后使用Assert验证预期值和实际值是否等于使用两个值格式化消息的位置。 HTH

int expected_x_value = 123;
int actual_x_value = 0;

var mock = new Mock<IDoSomethingUseful>();
mock.Setup(m => m.Move(It.IsAny<MyVector>()))
    .Callback<MyVector>(
        (v) => 
        {
            actual_x_value = v.x;
        }
    );

var sut = new Thingy(mock.Object);
sut.CallDoSomethingUseful();

Assert.AreEqual(expected_x_value, actual_x_value, 
    string.Format("myVector.x was expected to be called with x = '{0}' but was '{1}'", 
                   expected_x_value, actual_x_value));