Mockito’s given() method configures a mock’s behavior for a specified method call. Use it to set up dependencies before exercising the code under test. section 15.2
Stub a repository lookup
given(accountRepository.findById(1L)).willReturn(Optional.of(sender)); sets up the mock to return a sender account when findById(1L) is called. The test can then call transferMoney() and verify the repository interactions. 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
}
}See given() configure both account lookups before the transfer service runs. section 15.2
