liveBook · Manning

ExtendWith

As explained in Spring Start Here, Second Edition

The JUnit Jupiter @ExtendWith annotation registers one or more extensions that integrate with the test lifecycle.

@ExtendWith registers a test extension. With MockitoExtension, it lets Mockito process @Mock and @InjectMocks fields, creating mocks and injecting them into the object under test. 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 annotation applied to a transfer-service test with mocked dependencies. section 15.2

How Spring Start Here, Second Edition covers it

How deep it goes
Explains the annotation’s role in enabling Mockito field handling, without detailing extension internals.
Examples
Uses transfer-service and login-controller unit tests with MockitoExtension.
What you can do after
Configure Mockito-managed mocks and the tested object in a unit-test class.
How it connects
Connects JUnit Jupiter extensions with Mockito, @Mock, and @InjectMocks.

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.