liveBook · Manning

assertThrows

As explained in Spring Start Here, Second Edition

The JUnit assertion method assertThrows() executes code and verifies that it throws an expected exception type.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Defines how the assertion executes the method and checks its exception type, while leaving side-effect checks to separate verifications.
Examples
Tests a missing transfer destination by expecting AccountNotFoundException and verifying that no account change occurs.
What you can do after
Apply JUnit's assertThrows() to check an expected exception, and use a separate verification to check for unwanted interactions.
How it connects
Connects exception handling in unit testing with JUnit assertions and Mockito interaction verification.

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.