Verifying the method invocation count with atLeast()

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

Getting ready

For this recipe, our system under test will be the same, TaxUpdater, as presented in the previous recipe; let's take another look at it:

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 mocked object's method was called at least a given number of times, call Mockito.verify(mock, VerificationMode.atLeast(count)).methodToVerify(...).

Let's check the JUnit test that verifies whether the web service's method has been called at least 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_least_two_messages_through_the_web_service() {
        // when
        systemUnderTest.updateTaxFactorFor(new Person(), new Person());

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

}

How it works...

Since the atLeast(…) verification works in a similar way to the times(…) verification, please refer to the How it works... section of the previous recipe for more details.

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

There's more...

To verify whether the method has been executed at least once, you can write it as follows:

verify(taxService, atLeastOnce()).updateMeanTaxFactor(any(Person.class), anyDouble());

See also

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

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