liveBook · Manning

Mockito

As explained in Spring Start Here, Second Edition

Mockito is a Java mocking framework for creating configurable test doubles and verifying their interactions.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Demonstrates mock creation, stubbing, interaction verification, annotations, and exception-flow checks without detailing framework internals.
Examples
Tests money transfers and login outcomes, including repository calls and missing-account exceptions.
What it assumes
Assumes Java classes and unit-test scenarios; demonstrates controlling dependencies instead of using a real repository.
What you can do after
Apply it via mock(), given(), and verify() to control collaborators and check tested-method interactions.
How it connects
Connects Mockito with JUnit, unit testing, dependency isolation, and Spring application services.

Also explained in

Compare how 4 books explain Mockito →

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.