Verifying interactions and ignoring stubbed methods

In this recipe, we will perform the verification of the interaction with a mock, but at the same time, we will ignore the stubbed methods from this verification.

Getting ready

For this recipe, our system under test will be a TaxTransferer class that will transfer tax through the web service for the given person if this person is not null. It will send a statistics report regardless of the fact whether the transfer took place or not:

public class TaxTransferer {

    private final TaxService taxService;

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

    public boolean transferTaxFor(Person person) {
        if(person != null) {
            taxService.transferTaxFor(person);
        }
        return taxService.sendStatisticsReport();
    }

}

How to do it…

To verify a mock's behavior in such a way that Mockito ignores the stubbed methods, you have to either call Mockito.verifyNoMoreInteractions(Mockito.ignoreStubs(mocks...)); or InOrder.verifyNoMoreInteractions(Mockito.ignoreStubs(mocks...));.

Let's test the system under test using JUnit; see Chapter 1, Getting Started with Mockito, for the TestNG configuration (I'm using the BDDMockito.given(...) and AssertJ's BDDAssertions.then(...) static methods; check out Chapter 7, Verifying Behavior with Object Matchers, for details on how to work with AssertJ or how to do the same with Hamcrest's assertThat(...) method):

@RunWith(MockitoJUnitRunner.class)
public class TaxTransfererTest {

    @Mock TaxService taxService;

    @InjectMocks TaxTransferer systemUnderTest;

    @Test
  public void should_verify_that_ignoring_stubbed_method_there_was_a_single_interaction_with_mock() {
      // given
      Person person = new Person();
      given(taxService.sendStatisticsReport()).willReturn(true);
  
      // when
      boolean success = systemUnderTest.transferTaxFor(person);
  
      // then
      verify(taxService).transferTaxFor(person);
      verifyNoMoreInteractions(ignoreStubs(taxService));
      then(success).isTrue();
    }
   }

How it works...

When you call Mockito.ignoreStubs(Object... mocks), Mockito goes through all the provided mocks and then marks invocations on their methods so that if they get stubbed, then they should be ignored for verification.

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.225.55.193