liveBook · Manning

MockitoExtension

As explained in Spring Start Here, Second Edition

MockitoExtension is a JUnit Jupiter extension that initializes Mockito annotations and integrates Mockito with test execution.

MockitoExtension enables Mockito to read @Mock and @InjectMocks annotations on a test class and control those fields. Use it to avoid creating mock dependencies and the tested object inside each test method. section 15.2

Listing 15.5 Using annotations for mock dependencies
@ExtendWith(MockitoExtension.class)   #A
public class TransferServiceWithAnnotationsUnitTests {
 
  @Mock    #B
  private AccountRepository accountRepository;
 
  @InjectMocks  #C
  private TransferService transferService;
 
  @Test
  public void moneyTransferHappyFlow() {
    Account sender = new Account();
    sender.setId(1);
    sender.setAmount(new BigDecimal(1000));
 
    Account destination = new Account();
    destination.setId(2);
    destination.setAmount(new BigDecimal(1000));
 
    given(accountRepository.findById(sender.getId()))
        .willReturn(Optional.of(sender));
 
    given(accountRepository.findById(destination.getId()))
        .willReturn(Optional.of(destination));
 
    transferService.transferMoney(1, 2, new BigDecimal(100));
 
    verify(accountRepository)
      .changeAmount(1, new BigDecimal(900));
 
    verify(accountRepository)
      .changeAmount(2, new BigDecimal(1100));
  }
}

See the extension alongside @Mock and @InjectMocks in a transfer-service unit test. section 15.2

How Spring Start Here, Second Edition covers it

How deep it goes
Explains how the extension supports @Mock and @InjectMocks, without detailing its internals.
Examples
Demonstrates the extension in transfer-service and login-controller tests.
What you can do after
Apply MockitoExtension with @Mock and @InjectMocks to prepare annotated test fields.
How it connects
Connects Mockito annotations with unit testing and dependency control.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.