When using Moq Verify() method invocation count, have failing test's error message contain actual method invocation count using Moq

此生再无相见时 提交于 2019-12-01 14:32:29

问题


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:

Moq.MockException: Invocation was not performed on the mock 1 times: e => e.Blink()

What would be better is something like:

Moq.MockException: Invocation was unexpectedly performed 2 times, not 1 time: e => e.Blink()

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();
    }
}

Is it possible to harvest and display the actual number of times the dependency's method was called, in the failing test's error message?

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…)


回答1:


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


来源:https://stackoverflow.com/questions/16693078/when-using-moq-verify-method-invocation-count-have-failing-tests-error-messa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!