问题描述
考虑以下情况,我正在测试注入依赖项的方法被调用特定次数:
Consider the following, where I am testing that an injected dependency's method is called a specific number of times:
[Fact]
public void WhenBossTalksEmployeeBlinksTwice()
{
// arrange
var employee = new Mock<IEmployee>();
employee.Setup(e => e.Blink());
var boss = new Boss(employee.Object);
// act
boss.Talk();
// assert
employee.Verify(e => e.Blink(), Times.Exactly(2)); // Passes as expected
employee.Verify(e => e.Blink(), Times.Exactly(1)); // Fails as expected
}
当我强制测试失败时,输出为:
When I force the failing test, the output is:
更好的方法是:
以下是与测试有关的项目:
Here are the items involved with the test:
public interface IEmployee { void Blink(); }
public class Boss {
private readonly IEmployee _employee;
public Boss(IEmployee employee) { _employee = employee; }
public void Talk() {
_employee.Blink();
_employee.Blink();
}
}
是否可以在失败的测试的错误消息中收集并显示依赖项方法被调用的实际次数?
我不确定是否很重要,但是我正在使用Moq v3.1.416.3(我知道不是最新的,但是我正在使用的另一个库尚未更新到Moq 4.x ...)
I'm not sure that it matters, but I'm using Moq v3.1.416.3 (not the latest, I know, but another library I'm using hasn't updated to Moq 4.x yet…)
推荐答案
我不知道在Moq3中收集信息的直接方法.我要做的是在Blink的设置上使用回调
I don't know of a straight way to harvest the information in Moq3. what I would do is use a callback on the setup of Blink
int count = 0;
employee.Setup(e => e.Blink()).Callback(() => count++);
...
employee.Verify(e => e.Blink(), Times.Exactly(1), "Moq.MockException: Invocation was unexpectedly performed " + count + " times, not 1 time: e => e.Blink()"); // Fails as expected
这篇关于使用Moq Verify()方法调用计数时,测试失败的错误消息包含使用Moq的实际方法调用计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!