liveBook · Manning

Unit test

As explained in Spring Start Here, Second Edition

A unit test checks the behavior of a small, isolated unit of code.

A unit test checks a small piece of logic in isolation. It calls the logic under controlled conditions and verifies that its behavior matches the requirements. Unit tests are typically short and fast, and a failure helps narrow down where a problem lies. section 15.2

Unit tests also help protect existing behavior as an application changes and can serve as documentation. They complement integration tests, which check whether components work together; components that pass separately can still fail when connected. section 15.0 section 15.4

A unit test has three main parts:

  • Assumptions: Choose the inputs and control how dependencies behave. A mock is a fake object whose behavior the test controls. section 15.4
  • Execution: Call the method being tested with those inputs. section 15.4
  • Validation: Check the result or verify that the method interacted with its dependencies as expected. section 15.2

Testing a money transfer

To test a transfer in isolation, replace the account repository with a mock. Give the sender and receiver balances of 1,000, configure the mock to return those accounts, and transfer 100. Then verify that the service asks the repository to update the balances to 900 and 1,100. section 15.2

Listing 15.4 A unit test validating the happy flow
public class TransferServiceUnitTests {
 
  // Omitted code
 
 @Test
    public void transferMoneyHappyFlow() {
    Account sender = new Account();
    sender.setId(1L);
    sender.setAmount(new BigDecimal("1000"));
 
    Account receiver = new Account();
    receiver.setId(2L);
    receiver.setAmount(new BigDecimal("1000"));
 
    given(accountRepository.findById(1L))
      .willReturn(Optional.of(sender));
 
    given(accountRepository.findById(2L))
      .willReturn(Optional.of(receiver));
 
    transferService.transferMoney(1L, 2L, new BigDecimal("100")); 
 
    verify(accountRepository)     #A
      .changeAmount(1L, new BigDecimal("900"));    #A
    verify(accountRepository)     #A
      .changeAmount(2L, new BigDecimal("1100"));     #A
  }
}

See the assumptions, method call, and repository verifications together in the transfer test. section 15.2

Test error paths as well as the happy flow. If the receiver account is missing, the transfer should throw an AccountNotFoundException and should not ask the repository to change either balance. 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());
  }
}

See how assertThrows checks the exception and verify with never checks that no balance update was requested. section 15.2

Mocks can also isolate a controller. For a login action, configure the login processor to report success or failure, then check the returned view and verify the corresponding message added to the model. section 15.2

In Java, JUnit and Mockito support these tests. A setup method can create a mock and pass it to the object under test; alternatively, Mockito annotations can create and inject mocks. An IDE can run an individual test class or the project’s tests and display their statuses. section 15.2

How Spring Start Here, Second Edition covers it

How deep it goes
Works through assumptions, execution, and validation, including mock setup, interaction verification, returned values, and exception flows.
Examples
Tests money transfer balances and a missing account, plus successful and failed login controller actions.
What you can do after
Apply unit testing via JUnit and Mockito to control dependencies and verify method behavior.
How it connects
Connects unit testing to mocks, integration testing, assertions, dependency injection, and exception handling.

Also explained in

Compare how 18 books explain unit test →

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.