Use Mockito’s @Mock annotation to have a mock dependency created for a test field instead of creating it manually. Add @ExtendWith(MockitoExtension.class) to the test class so Mockito can process the annotation; pair it with @InjectMocks to create the object under test and inject its mocks. 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 annotations applied to a mocked repository and the service under test in a money-transfer test. section 15.2
