我有以下测试代码。
var test = "Test";
var command = new MyCommand { V = test };
var mock = new Mock<IRepository>(); // IRepository has the method of Save()
var p = new P(test);
mock.Setup(x => x.Save(p)).Verifiable();
var sut = new C(mock.Object);
var result = await sut.M(command);
mock.Verify();
测试应通过。但是,它失败并显示错误,
Message: Moq.MockException : Mock: This mock failed verification due to the following: IRepository x => x.Save(P): This setup was not matched. Stack Trace: Mock.Verify()
sut.M()
将字符串X转换为类型为P
的类型P(X)
。
答案 0 :(得分:1)
在我看来,您想验证模拟对象中的Save方法是使用特定值而不是类型进行调用的。
我尝试了以下类似方法,并认为它应该可以工作。我已经修改了您的示例。
var test = "Test";
var command = new MyCommand { V = test };
var mock = new Mock<IRepository>();
IRepository has the method of Save()
var p = new P(test);
mock.Setup(x => x.Save(It.IsAny<P>());
var sut = new C(mock.Object);
var result = await sut.M(command);
mock.Verify(x => x.Save(It.Is<P>(v => v.Value.Equals(p.Value))), Times.AtLeastOnce);
这将测试特定属性的值是否相等。
我用以下测试对此进行了测试:
var test = "Test";
var mock = new Mock<ITestRepository>(); // ITestRepository has the method of Save()
var p = new P(test);
mock.Setup(x => x.Save(It.IsAny<P>()));
mock.Object.Save(new P(test));
mock.Verify(x => x.Save(It.Is<P>(v => v.Value.Equals(p.Value))), Times.AtLeastOnce);