Verifying the method invocation count with atMost()

In this recipe, we will verify whether a method on a mock was executed, at most, a specified number of times.

Getting ready

As shown in the following code, our system under test is TaxUpdater (the same as that presented in the previous recipes):

public class TaxUpdater {

    static final double MEAN_TAX_FACTOR = 10.5;

    private final TaxService taxService;

    public TaxUpdater(TaxService taxService) {
        this.taxService = taxService;
    }

    public void updateTaxFactorFor(Person brother, Person sister) {
        taxService.updateMeanTaxFactor(brother, calculateMeanTaxFactor());
        taxService.updateMeanTaxFactor(sister, calculateMeanTaxFactor());
    }

    private double calculateMeanTaxFactor() {
        return MEAN_TAX_FACTOR;
    }

}

How to do it...

To verify whether the mock's method was invoked at most a given number of times, call Mockito.verify(mock, VerificationMode.atMost(count)).methodToVerify(...).

Let's check the JUnit test that verifies whether the web service's method has been called at most twice (see Chapter 1, Getting Started with Mockito, for the TestNG configuration):

@RunWith(MockitoJUnitRunner.class)
public class TaxUpdaterTest {

    @Mock TaxService taxService;

    @InjectMocks TaxUpdater systemUnderTest;

    @Test
    public void should_send_at_most_two_messages_through_the_web_service() {
        // when
        systemUnderTest.updateTaxFactorFor(new Person(), new Person());

        // then
        verify(taxService, atMost(2)).updateMeanTaxFactor(any(Person.class), anyDouble());
    }

}

How it works...

Since the atMost(…) verification works in a similar way to the times(…) verification, please refer to the How it works... section of the Verifying the method invocation count with times() recipe for more details.

The difference between the two is that in this recipe, we have the AtMost VerificationMode that first stores the expected number of method invocations and then, on verification, it checks whether that method actually got executed at most that many times. If that isn't the case, an exception will be thrown.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.134.17