How do you use the @SpringBootTest and @MockBean annotations?

@SpringBootTest and @MockBean are commonly used together in Spring Boot testing to verify application behavior while controlling dependencies. @SpringBootTest loads the complete Spring application context, whereas @MockBean replaces specific Spring beans with Mockito mocks for isolated and predictable testing.

Key Points

Example

Suppose we want to test OrderService, but it depends on PaymentService.

Instead of calling the actual PaymentService, we can replace it with a mock and control its behavior during the test.

@SpringBootTest
class OrderServiceTest {

    @Autowired
    private OrderService orderService;

    @MockBean
    private PaymentService paymentService;

    @Test
    void shouldCreateOrderSuccessfully() {
        when(paymentService.processPayment())
                .thenReturn("SUCCESS");

        String result =
                orderService.placeOrder();

        assertEquals(
                "Order Created",
                result);
    }
}

@SpringBootTest:

Purpose

Features

Common Usage

Example

@SpringBootTest
class ApplicationIntegrationTest {
}

@MockBean:

Purpose

Features

Common Usage

Example

@MockBean
private UserRepository userRepository;

Comparison

@SpringBootTest

@MockBean

Real-World Example

User Registration Service

Dependencies

During testing

This allows testing business logic without sending actual emails or notifications.

Best Practice

Interview Tip

A concise interview answer is: @SpringBootTest loads the complete Spring Boot application context and is mainly used for integration testing. @MockBean creates a Mockito mock and replaces the actual Spring bean in the application context, allowing dependencies to be isolated during tests. Together, they help test application behavior without relying on real external systems.

Last updated: 11 November 2026

Previous question: How do you approach testing in Spring Boot applications?

Next question: What advantages does YAML offer over properties files in Spring Boot? Are there limitations when using YAML for configuration?

More Spring Boot - Level II interview questions

All Spring Boot - Level II questions