liveBook · Manning

@InjectMocks annotation

As explained in Spring Start Here, Second Edition

The Mockito @InjectMocks annotation marks an object for creation with mock dependencies injected into its constructor, fields, or methods.

@InjectMocks marks the object under test so Mockito creates it and injects dependencies marked with @Mock. Use it with @ExtendWith(MockitoExtension.class), which enables processing of those annotations. 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 pattern in a money-transfer unit test: a mocked repository is injected into the service under test. section 15.2

How Spring Start Here, Second Edition covers it

How deep it goes
Defines mock injection into the tested object's parameters but does not explain injection selection or internals.
Examples
Uses a money-transfer service and a login controller as annotation-based unit-test examples.
What it assumes
Requires @Mock dependencies and @ExtendWith(MockitoExtension.class) to enable annotation processing.
What you can do after
Apply via Mockito annotations to create a tested service or controller with mock dependencies for unit tests.
How it connects
Connects Mockito, @Mock, MockitoExtension, and unit testing.

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.