BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Testing
.NET 3.5+

Verifying the Number of Calls to a Mocked Method

The use of mock objects within unit tests allows you to verify that the correct calls to dependencies are made when a test is run. Rather than simply checking that a call is made, it is often essential to check how many times a method was executed.

Testing a Range of Call Counts

Sometimes you will not be able to determine the exact number of calls that should be made during a unit test but you will want to test that the number falls within a given range. Five methods are provided for this purpose. They are:

  • AtLeastOnce. Passes if the call is made one or more times and fails if the call is not made at all. This provides the same functionality as if the Times parameter was omitted.
  • AtLeast. Used with an integer parameter, the verification passes if the method is executed at least the provided number of times. If fewer calls are made, the test fails.
  • AtMostOnce. Passes if the method is called once or not at all. If there are two or more calls, the test fails.
  • AtMost. As with AtLeast, this method requires an integer argument. This time the argument specifies the maximum number of times the method must be called for the test to pass.
  • Between. The Between method defines a range of values by specifying a starting value, an ending value and an option that determines whether the range is inclusive or exclusive. If the number of calls falls outside of the range the test fails. If the number of calls matches the maximum or minimum values when the range is exclusive, the test also fails.

The last code sample shows three tests that use a combination of the above options. Although these tests are not realistic for the ChangeReturner class, they do demonstrate the use and syntax of the Verify method.

[Test]
public void WhenReturningFourPence()
{
    _returner.GiveChange(4);
    _mockCoinRelease.Verify(m => m.Release(2), Times.AtLeastOnce());
    _mockCoinRelease.Verify(m => m.Release(2), Times.AtLeast(1));
    _mockCoinRelease.Verify(m => m.Release(2), Times.AtLeast(2));
}

[Test]
public void WhenReturningOnePound()
{
    _returner.GiveChange(100);
    _mockCoinRelease.Verify(m => m.Release(100), Times.AtMostOnce());
    _mockCoinRelease.Verify(m => m.Release(100), Times.AtMost(1));
    _mockCoinRelease.Verify(m => m.Release(100), Times.AtMost(2));
}

[Test]
public void WhenReturningFortyPence()
{
    _returner.GiveChange(40);
    _mockCoinRelease.Verify(m => m.Release(20), Times.Between(1, 3, Range.Exclusive));
    _mockCoinRelease.Verify(m => m.Release(20), Times.Between(1, 3, Range.Inclusive));
}
11 June 2011