In this recipe, we will verify that a specified method on a mock was executed and then any interactions stopped taking place.
For this recipe, our system under test will be a TaxTransferer
class that will transfer tax for a non-null person. If the passed person value is null, then an error report is sent:
public class TaxTransferer { private final TaxService taxService; public TaxTransferer(TaxService taxService) { this.taxService = taxService; } public void transferTaxFor(Person person) { if (person == null) { taxService.sendErrorReport(); return; } taxService.transferTaxFor(person); } }
To verify that the only method executed on a mock is the one provided by us, you have to call Mockito.verify(mock, VerificationMode.only()).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 TaxTransfererTest { @Mock TaxService taxService; @InjectMocks TaxTransferer systemUnderTest; @Test public void should_only_send_error_report_if_person_is_null() { // when systemUnderTest.transferTaxFor(null); // then verify(taxService, only()).sendErrorReport(); } }
When using the only()
verification mode in the Mockito.verify(…)
method, we are delegating the verification to the class named Only
. This class verifies whether there was a single invocation of the verified method and no other interactions with the mock took place. Mockito will throw a verification exception under the following conditions:
If neither of these cases are applicable, then the method invocation gets marked as verified. It's pretty important in terms of greedy verification. (We'll go back to this in more detail in the later parts of this chapter.)
You can also define that interactions should stop happening by using a less elegant approach. The following code sample is presented only for you to know that you can refactor it to the one presented earlier:
@RunWith(MockitoJUnitRunner.class) public class TaxTransfererTest { @Mock TaxService taxService; @InjectMocks TaxTransferer systemUnderTest; @Test public void should_only_send_error_report_if_person_is_null_in_an_ugly_way() { // when systemUnderTest.transferTaxFor(null); // then verify(taxService).sendErrorReport(); verifyNoMoreInteractions (taxService); } }
18.226.185.196