liveBook · Manning

Verify() method

As explained in Spring Start Here, Second Edition

The Mockito verify() method checks whether a specified interaction with a mock occurred.

Mockito’s verify() checks whether a mock received an expected method call, including its arguments. In a money-transfer test, it checks that the repository updates both account balances; with never(), it can check that no update occurred. 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 verify() check the repository calls and their expected account IDs and balances after a transfer. section 15.2

How Spring Start Here, Second Edition covers it

How deep it goes
Defines interaction verification and demonstrates expected arguments and a never() check, without detailing Mockito internals.
Examples
Checks repository balance updates in a transfer test and a message added to a login model.
What it assumes
Builds on mock objects, stubbing, and invoking the tested method before checking interactions.
What you can do after
Evaluate whether a tested method made the expected calls to its mocked dependencies.
How it connects
Connects mock objects and unit testing with stubbing and method execution.

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.