Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 812
Jeff Avatar asked May 22 '13 13:05

Jeff


People also ask

What is verify in Moq?

Verifies that all verifiable expectations have been met.

What can be mocked with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

Is Moq a unit test?

The Moq framework is an open source unit testing framework that works very well with . NET code and Phil shows us how to use it.


1 Answers

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
like image 195
rivarolle Avatar answered Sep 17 '22 14:09

rivarolle