16

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

Jeff
  • 2,191
  • 4
  • 30
  • 49
  • 4
    +1 for the example code :) – ljubomir May 06 '14 at 07:52
  • 4
    Since I found this in my googling, I thought I would provide an update. In Moq v4.1 (and maybe in all 4.x) you get something like: "expected invocation on the mock once but was 0 times". So the answer to this question is now out of the box. – Nathan Cooper Oct 08 '14 at 09:33

1 Answers1

21

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
Pang
  • 9,564
  • 146
  • 81
  • 122
rivarolle
  • 1,528
  • 11
  • 18