When a method should fail in a particular way, `assertThrows()` runs it and checks that it throws the expected exception type. In an exception-flow test, it verifies the failure; pair it with a separate interaction check when you also need to ensure the method caused no unwanted change. section 15.2
Listing 15.6 Testing an exception flow
@ExtendWith(MockitoExtension.class)
public class TransferServiceWithAnnotationsUnitTests {
@Mock
private AccountRepository accountRepository;
@InjectMocks
private TransferService transferService;
@Test
public void moneyTransferDestinationAccountNotFoundFlow() {
Account sender = new Account();
sender.setId(1);
sender.setAmount(new BigDecimal(1000));
given(accountRepository.findById(1L))
.willReturn(Optional.of(sender));
given(accountRepository.findById(2L))
.willReturn(Optional.empty()); #A
assertThrows(
AccountNotFoundException.class, #B
() -> transferService.transferMoney(1, 2, new BigDecimal(100))
);
verify(accountRepository, never()) #C
.changeAmount(anyLong(), any());
}
}The transfer test expects AccountNotFoundException when the destination account is missing, then verifies that no account change was made. section 15.2
