Mockito creates controllable mock objects that replace real dependencies in unit tests. Define how a mock responds, run the method under test, then verify its interactions. section 15.2
A typical mock-based test follows three steps:
- Create a mock dependency and configure its responses for chosen inputs. section 15.2
- Call the method being tested, then verify expected calls and arguments. section 15.2
- Test failure paths too, checking that forbidden interactions do not occur. section 15.2
Money transfer
Stub an account repository to return sender and receiver accounts. After a transfer of 100, verify that the repository receives updated amounts of 900 and 1,100. section 15.2
Listing 15.3 A unit test validating the happy flow
public class TransferServiceUnitTests {
// Omitted code
@Test
@DisplayName("""
GIVEN a valid sender and receiver account
WHEN transferMoney is called
THEN the amounts are updated for both accounts
""")
public void transferMoneyHappyFlow() {
Account sender = new Account(); #A
sender.setId(1L); #A
sender.setAmount(new BigDecimal("1000")); #A
Account receiver = new Account(); #A
receiver.setId(2L); #A
receiver.setAmount(new BigDecimal("1000")); #A
given(accountRepository.findById(1L)) #B
.willReturn(Optional.of(sender)); #B
given(accountRepository.findById(2L)) #C
.willReturn(Optional.of(receiver)); #C
transferService.transferMoney(1L, 2L, new BigDecimal("100")); #D
}
}A happy-path test shows repository responses being configured before the transfer method is called. section 15.2



