A Spring integration test can use real application components while replacing a dependency that the test does not need to exercise. @MockitoBean creates a Mockito mock and adds it to the Spring application context, replacing an existing bean when one matches. section 16.1 section 16.4
Unlike @Mock in a unit test, @MockitoBean makes the mock available to Spring-managed beans. Use @SpringBootTest to start the context and @Autowired to inject the object under test; Spring can then supply the mock as its dependency. section 16.1 section 16.4
Control a repository in a transfer test
Declare the mock and inject the service: @SpringBootTest class TransferServiceSpringIntegrationTests { @MockitoBean private AccountRepository accountRepository; @Autowired private TransferService transferService; } The test can then configure accountRepository.findById(...) to return prepared accounts and exercise the injected service. The repository is controlled by the test, while Spring still creates and manages the service. section 16.1
Choose mocks according to the interaction you want to test. To check a service’s interaction with its real repository, keep that repository real. To test a controller and its web setup while controlling repository responses, replace the repository with a mock. section 16.1 section 16.2
Listing 16.3 Writing a test case
@SpringBootTest
public class TransferMoneyTests {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@MockitoBean
private AccountRepository accountRepository;
@BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test #A
@DisplayName("""
GIVEN Two accounts exist with IDs 1 and 2, and both have 1000 balance.
WHEN A transfer of 100 is requested from account 1 to account 2.
THEN The response status is OK and both accounts' balances are updated
""")
void transferMoneySuccess() throws Exception {
Account sender = new Account(); #B
sender.setId(1); #B
sender.setAmount(new BigDecimal("1000")); #B
Account receiver = new Account(); #B
receiver.setId(2); #B
receiver.setAmount(new BigDecimal("1000")); #B
given(accountRepository.findById(1L)) #B
.willReturn(Optional.of(sender)); #B
given(accountRepository.findById(2L)) #B
.willReturn(Optional.of(receiver)); #B
mockMvc.perform(post("/transfer") #C
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"senderAccountId": 1,
"receiverAccountId": 2,
"amount": 100
}
"""))
.andExpect(status().isOk());
verify(accountRepository) #D
.changeAmount(1L, new BigDecimal("900")); #D
verify(accountRepository) #D
.changeAmount(2L, new BigDecimal("1100")); #D
}
}See how a controller test combines @MockitoBean with MockMvc to control repository behavior while exercising the web layer. section 16.2

