使用起订量时,我遇到了一个非常奇怪的问题,即只有当我设置的方法是公开的时,模拟上的设置似乎才有效.我不知道这是 Moq 错误还是我只是有这个错误(Moq 的新手).这是测试用例:
Using Moq, I have a very odd issue where the setup on a mock only seems to work if the method I am setting up is public. I don't know if this is a Moq bug or if I just have this wrong (newbie to Moq). Here is the test case:
public class TestClass
{
public string Say()
{
return Hello();
}
internal virtual string Hello()
{
return "";
}
}
[TestMethod]
public void Say_WhenPublic_CallsHello()
{
Mock<TestClass> mock = new Mock<TestClass>();
mock.Setup(x => x.Hello()).Returns("Hello World");
string result = mock.Object.Say();
mock.Verify(x => x.Hello(), Times.Exactly(1));
Assert.AreEqual("Hello World", result);
}
失败并显示此消息:
Say_WhenPublic_CallsHello 失败:Moq.MockException:未在模拟上执行 1 次调用:x => x.Hello()在 Moq.Mock.ThrowVerifyException(预期 IProxyCall,表达式表达式,Times 次)...
Say_WhenPublic_CallsHello failed: Moq.MockException: Invocation was not performed on the mock 1 times: x => x.Hello() at Moq.Mock.ThrowVerifyException(IProxyCall expected, Expression expression, Times times)...
如果我像这样公开 Hello 方法,则测试通过.这里有什么问题?
If I make the Hello method public like this, the test passes. What is the issue here?
public virtual string Hello()
{
return "";
}
提前致谢!
当 Hello()
是 internal 时测试失败,因为在这种情况下 Moq 无法提供方法的覆盖.这意味着 Hello()
的内部实现将运行,而不是 mock 的版本,导致 Verify()
失败.
The test fails when Hello()
is internal because Moq cannot provide an override of the method in this case. This means that the internal implementation of Hello()
will run, rather than mock's version, causing the Verify()
to fail.
顺便说一句,您在这里所做的事情在单元测试的上下文中毫无意义.单元测试不应该关心 Say()
调用内部 Hello()
方法.这是程序集内部的实现,与使用代码无关.
Incidentally, what you are doing here makes no sense in the context of a unit test. A unit test should not care that Say()
calls an internal Hello()
method. This is implementation internal to your assembly and not a concern of consuming code.
这篇关于验证方法被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!