liveBook · Manning

Given() method

As explained in Spring Start Here, Second Edition

The Mockito given() method defines the behavior a mock exhibits when a specified method call occurs.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Defines behavior with worked return-value examples for repository lookups and login outcomes.
Examples
Stubs account lookups for a money transfer and login results for a controller test.
What you can do after
Apply it via Mockito to configure mock method returns for a test scenario.
How it connects
Connects Mockito mocks with unit testing and verification of method calls.

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.