Definition
- MockMvc is a class from the spring-test module that simulates HTTP requests (GET, POST, PUT, DELETE) and asserts on the response status, headers, and body without needing a running servlet container.
- @WebMvcTest is a test slice annotation that loads only the controller being tested, plus filters, exception handlers, and converters, while excluding services, repositories, and database configuration.
- @MockitoBean (Spring Boot 3.4+) replaces a real Spring bean with a Mockito mock in the test context, letting you control what the service returns.
- jsonPath is a response assertion that evaluates JSONPath expressions against the response body to verify specific fields.
- MockMvcResultMatchers provides static methods like status(), content(), jsonPath(), and header() for asserting response properties.
Think of testing a bank teller window. A full integration test (@SpringBootTest) opens the entire bank: tellers, vault, ledger system, and network. A MockMvc test (@WebMvcTest) tests only the teller window. You hand a deposit slip (HTTP request) to the teller (controller) and check that the teller fills out the receipt correctly (response). The vault and ledger (service and database) are replaced with stunt doubles (mocks) that return scripted answers. This is much faster because you do not need to open the vault or boot the ledger system.
Understanding the Concepts
What is MockMvc?
MockMvc is a test utility from the Spring Framework that lets you send HTTP requests to your controllers without starting an embedded server (Tomcat, Jetty). The request is processed through the Spring MVC dispatcher servlet in memory: it goes through filters, handler mapping, argument resolution, validation, and exception handling, just like a real request.
This means MockMvc tests verify the full web layer behavior: URL mapping, request parameter binding, JSON serialization/deserialization, validation annotations, and exception handler responses.
package com.bank.controller;
import com.bank.dto.AccountDTO;
import com.bank.service.AccountService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/{id}")
public AccountDTO getAccount(@PathVariable("id") String accountId) {
return accountService.findAccount(accountId);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public AccountDTO createAccount(@Valid @RequestBody CreateAccountRequest request) {
return accountService.createAccount(
request.holderName(), request.initialDeposit());
}
public record CreateAccountRequest(
@NotBlank(message = "Holder name is required")
String holderName,
@Positive(message = "Initial deposit must be positive")
BigDecimal initialDeposit
) {}
}
package com.bank.dto;
import java.math.BigDecimal;
public record AccountDTO(
String accountId,
String holderName,
BigDecimal balance,
String status
) {}
package com.bank.service;
import com.bank.dto.AccountDTO;
import java.math.BigDecimal;
public interface AccountService {
AccountDTO findAccount(String accountId);
AccountDTO createAccount(String holderName, BigDecimal initialDeposit);
}
Why do you need MockMvc instead of a real HTTP client?
MockMvc tests are faster and more isolated than tests that start a real server.
- Speed. MockMvc with @WebMvcTest starts in 1 to 2 seconds because it loads only the web layer. A @SpringBootTest with a full context and embedded server takes 10 to 30 seconds.
- Isolation. MockMvc tests focus on controller logic only. The service is mocked, so a database error or network issue cannot fail your controller test.
- Determinism. Mocked services return exactly what you tell them to, making tests predictable and repeatable.
- No port conflicts. No real server means no port binding, so multiple tests can run in parallel.
Test execution time comparison:
@WebMvcTest + MockMvc: ~1.5 seconds for 20 test methods
@SpringBootTest + real server: ~15 seconds for 20 test methods
In a CI pipeline running 500 controller tests:
MockMvc: ~35 seconds total
Full server: ~6 minutes total
How does @WebMvcTest work?
@WebMvcTest is a Spring Boot test slice annotation. It auto-configures only the beans relevant to the web layer:
- Controllers annotated with @RestController or @Controller
- @ControllerAdvice exception handlers
- Servlet filters
- WebMvcConfigurer implementations
- Message converters (Jackson JSON, etc.)
- Argument resolvers
- It does NOT load:
- @Service beans
- @Repository beans
- @Component beans (except filters and advice)
- DataSource, JPA, Flyway, or any persistence configuration
You must provide mock replacements for any service that the controller depends on.
package com.bank.controller;
import com.bank.dto.AccountDTO;
import com.bank.service.AccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import java.math.BigDecimal;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(AccountController.class)
class AccountControllerTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private AccountService accountService;
@Test
void shouldReturnAccount() throws Exception {
// Arrange: mock service returns a known account
AccountDTO account = new AccountDTO(
"SAV2001", "Rajesh Kumar",
new BigDecimal("75000.00"), "ACTIVE");
when(accountService.findAccount("SAV2001")).thenReturn(account);
// Act + Assert: send GET request and verify response
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accountId").value("SAV2001"))
.andExpect(jsonPath("$.holderName").value("Rajesh Kumar"))
.andExpect(jsonPath("$.balance").value(75000.00))
.andExpect(jsonPath("$.status").value("ACTIVE"));
}
}
Test output:
AccountControllerTest > shouldReturnAccount() PASSED
Time: 1.2 seconds (context startup + test execution)
How do you test a GET endpoint with MockMvc?
A GET endpoint test verifies that the controller maps the URL correctly, calls the service with the right argument, and returns the expected JSON response.
package com.bank.controller;
import com.bank.dto.AccountDTO;
import com.bank.service.AccountService;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import java.math.BigDecimal;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(AccountController.class)
class AccountControllerGetTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private AccountService accountService;
@Test
@DisplayName("GET /api/accounts/SAV2001 returns account details")
void shouldReturnAccountDetails() throws Exception {
AccountDTO account = new AccountDTO(
"SAV2001", "Rajesh Kumar",
new BigDecimal("75000.00"), "ACTIVE");
when(accountService.findAccount("SAV2001")).thenReturn(account);
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.accountId").value("SAV2001"))
.andExpect(jsonPath("$.holderName").value("Rajesh Kumar"))
.andExpect(jsonPath("$.balance").value(75000.00))
.andExpect(jsonPath("$.status").value("ACTIVE"));
// Verify that the service was called with the correct argument
verify(accountService).findAccount("SAV2001");
}
@Test
@DisplayName("GET /api/accounts/UNKNOWN returns 404")
void shouldReturn404ForUnknownAccount() throws Exception {
when(accountService.findAccount("UNKNOWN"))
.thenThrow(new AccountNotFoundException("UNKNOWN"));
mockMvc.perform(get("/api/accounts/UNKNOWN"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.message").value("Account not found: UNKNOWN"));
}
}
The 404 test requires an exception handler:
package com.bank.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(AccountNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> handleNotFound(AccountNotFoundException ex) {
return Map.of("message", ex.getMessage());
}
}
Test output:
shouldReturnAccountDetails() PASSED
shouldReturn404ForUnknownAccount() PASSED
How do you test a POST endpoint with validation errors?
The controller uses @Valid on the request body. When validation fails, Spring returns 400 Bad Request with error details. Your test should verify that invalid input is rejected and the error message is correct.
package com.bank.controller;
import com.bank.dto.AccountDTO;
import com.bank.service.AccountService;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import java.math.BigDecimal;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(AccountController.class)
class AccountControllerPostTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private AccountService accountService;
@Test
@DisplayName("POST /api/accounts creates account with valid input")
void shouldCreateAccountWithValidInput() throws Exception {
AccountDTO created = new AccountDTO(
"SAV2001", "Priya Sharma",
new BigDecimal("50000.00"), "ACTIVE");
when(accountService.createAccount("Priya Sharma", new BigDecimal("50000.00")))
.thenReturn(created);
String requestBody = """
{
"holderName": "Priya Sharma",
"initialDeposit": 50000.00
}
""";
mockMvc.perform(post("/api/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.accountId").value("SAV2001"))
.andExpect(jsonPath("$.holderName").value("Priya Sharma"))
.andExpect(jsonPath("$.balance").value(50000.00));
}
@Test
@DisplayName("POST /api/accounts returns 400 when holder name is blank")
void shouldReturn400WhenHolderNameBlank() throws Exception {
String requestBody = """
{
"holderName": "",
"initialDeposit": 50000.00
}
""";
mockMvc.perform(post("/api/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isBadRequest());
// Verify service was never called with invalid input
verify(accountService, never()).createAccount(any(), any());
}
@Test
@DisplayName("POST /api/accounts returns 400 when deposit is negative")
void shouldReturn400WhenDepositNegative() throws Exception {
String requestBody = """
{
"holderName": "Rajesh Kumar",
"initialDeposit": -1000.00
}
""";
mockMvc.perform(post("/api/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isBadRequest());
verify(accountService, never()).createAccount(any(), any());
}
}
Test output:
shouldCreateAccountWithValidInput() PASSED
shouldReturn400WhenHolderNameBlank() PASSED
shouldReturn400WhenDepositNegative() PASSED
How do you mock the service layer with @MockitoBean?
@MockitoBean (introduced in Spring Boot 3.4, replacing @MockBean) creates a Mockito mock and registers it as a Spring bean, replacing the real service in the application context.
The mock returns null or default values by default. You use when(...).thenReturn(...) to define behavior for specific inputs, and verify(...) to check that the service was called correctly.
@WebMvcTest(AccountController.class)
class AccountControllerMockDemo {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private AccountService accountService;
@Test
@DisplayName("Service is called with correct account ID")
void shouldPassAccountIdToService() throws Exception {
AccountDTO account = new AccountDTO(
"SAV2001", "Rajesh Kumar",
new BigDecimal("75000.00"), "ACTIVE");
when(accountService.findAccount("SAV2001")).thenReturn(account);
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk());
// Verify the exact argument passed to the service
verify(accountService).findAccount("SAV2001");
}
@Test
@DisplayName("Service exception maps to 500")
void shouldReturn500WhenServiceThrows() throws Exception {
when(accountService.findAccount("SAV2001"))
.thenThrow(new RuntimeException("Database connection failed"));
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isInternalServerError());
}
}
Key @MockitoBean behaviors:
accountService.findAccount("SAV2001") -> returns what you configure
accountService.findAccount("OTHER") -> returns null (default)
accountService.createAccount(any(), any()) -> returns null (default)
verify(accountService).findAccount("SAV2001")
-> passes if findAccount was called exactly once with "SAV2001"
-> fails if not called, or called with a different argument
How is @WebMvcTest different from @SpringBootTest?
| Feature | @WebMvcTest | @SpringBootTest |
|---|---|---|
| What it loads | Controller, filters, advice, converters only | Full application context (all beans) |
| Server | No real server, in-memory dispatch | Can start embedded server with webEnvironment |
| Service/Repository beans | Not loaded, must be mocked | Loaded from real classes |
| Database | Not configured | Full DataSource, JPA, Flyway |
| Speed | Fast (1 to 2 seconds) | Slow (10 to 30 seconds) |
| Scope | Controller input/output behavior | Full integration, end-to-end |
| Best for | Unit-testing controller logic | Integration testing full request flow |
// @WebMvcTest: fast, isolated, mocks the service
@WebMvcTest(AccountController.class)
class AccountControllerTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private AccountService accountService; // mock
@Test
void testGetAccount() throws Exception {
when(accountService.findAccount("SAV2001"))
.thenReturn(new AccountDTO("SAV2001", "Rajesh",
new BigDecimal("75000"), "ACTIVE"));
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk());
}
}
// @SpringBootTest: full context, real service, real database
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class AccountIntegrationTest {
@Autowired
private TestRestClient restClient;
@Test
void testGetAccountEndToEnd() {
// This calls the real service, which calls the real database
AccountDTO account = restClient.get()
.uri("/api/accounts/SAV2001")
.retrieve()
.body(AccountDTO.class);
assertThat(account.accountId()).isEqualTo("SAV2001");
}
}
@WebMvcTest context startup: ~1.5 seconds
@SpringBootTest context startup: ~12 seconds (with H2 + Flyway)
Recommendation:
Use @WebMvcTest for controller logic (URL mapping, validation, serialization).
Use @SpringBootTest for critical end-to-end paths (full transfer flow).
How do you test JSON response structure with jsonPath?
jsonPath uses JSONPath expressions to navigate the response JSON and assert on specific fields. This is more precise than comparing the entire JSON string, because it ignores field order and extra fields.
@Test
@DisplayName("Response JSON structure is correct")
void shouldReturnCorrectJsonStructure() throws Exception {
AccountDTO account = new AccountDTO(
"SAV2001", "Rajesh Kumar",
new BigDecimal("75000.00"), "ACTIVE");
when(accountService.findAccount("SAV2001")).thenReturn(account);
mockMvc.perform(get("/api/accounts/SAV2001"))
// Verify individual fields
.andExpect(jsonPath("$.accountId").value("SAV2001"))
.andExpect(jsonPath("$.holderName").value("Rajesh Kumar"))
.andExpect(jsonPath("$.balance").value(75000.00))
.andExpect(jsonPath("$.status").value("ACTIVE"))
// Verify field existence
.andExpect(jsonPath("$.accountId").exists())
.andExpect(jsonPath("$.password").doesNotExist())
// Verify field types
.andExpect(jsonPath("$.holderName").isString())
.andExpect(jsonPath("$.balance").isNumber());
}
For list responses, jsonPath supports array assertions:
@Test
@DisplayName("List accounts returns correct array")
void shouldReturnAccountList() throws Exception {
List<AccountDTO> accounts = List.of(
new AccountDTO("SAV2001", "Rajesh Kumar",
new BigDecimal("75000.00"), "ACTIVE"),
new AccountDTO("SAV2002", "Priya Sharma",
new BigDecimal("120000.00"), "ACTIVE")
);
when(accountService.findAllAccounts()).thenReturn(accounts);
mockMvc.perform(get("/api/accounts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(2))
.andExpect(jsonPath("$[0].accountId").value("SAV2001"))
.andExpect(jsonPath("$[1].accountId").value("SAV2002"))
.andExpect(jsonPath("$[0].balance").value(75000.00));
}
Common jsonPath expressions:
$.accountId -> root field
$.balance -> numeric field
$[0].accountId -> first element of array
$.length() -> array size
$..accountId -> all accountId fields (deep search)
$.accountId.length() -> string length
What are common mistakes?
Mistake 1: Using @SpringBootTest when @WebMvcTest is enough
WRONG: Loading the full application context just to test controller mapping.
// WRONG: Loads database, Flyway, Kafka, Redis, and everything else.
// Takes 15 seconds to start. Fails if database is not available.
@SpringBootTest
@AutoConfigureMockMvc
class AccountControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetAccount() throws Exception {
// This test only checks URL mapping and JSON output,
// but it loaded the entire application context.
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk());
}
}
CORRECT: Use @WebMvcTest for controller-level tests.
// CORRECT: Loads only the web layer. Fast. No database needed.
@WebMvcTest(AccountController.class)
class AccountControllerTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private AccountService accountService;
@Test
void testGetAccount() throws Exception {
when(accountService.findAccount("SAV2001"))
.thenReturn(new AccountDTO("SAV2001", "Rajesh",
new BigDecimal("75000"), "ACTIVE"));
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk());
}
}
Mistake 2: Not setting Content-Type on POST requests
WRONG: Sending a POST without Content-Type. Spring returns 415 Unsupported Media Type.
// WRONG: No content type specified
mockMvc.perform(post("/api/accounts")
.content("{\"holderName\": \"Rajesh\", \"initialDeposit\": 50000}"))
.andExpect(status().isCreated());
// Actual result: 415 Unsupported Media Type
CORRECT: Always set the Content-Type header.
// CORRECT: Content-Type set to application/json
mockMvc.perform(post("/api/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"holderName\": \"Rajesh\", \"initialDeposit\": 50000}"))
.andExpect(status().isCreated());
Mistake 3: Forgetting to mock the service return value
WRONG: The mock returns null by default, causing a NullPointerException in the controller.
// WRONG: No when().thenReturn() configured
@Test
void testGetAccount() throws Exception {
// accountService.findAccount("SAV2001") returns null by default
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk()); // FAILS: 500 due to NPE
}
CORRECT: Always configure mock behavior before the request.
// CORRECT: Mock configured with expected return value
@Test
void testGetAccount() throws Exception {
when(accountService.findAccount("SAV2001"))
.thenReturn(new AccountDTO("SAV2001", "Rajesh",
new BigDecimal("75000"), "ACTIVE"));
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk());
}
How do you test security and authorization?
When your controller requires authentication, @WebMvcTest loads Spring Security auto-configuration by default. You can use @WithMockUser to simulate an authenticated user, or test that unauthenticated requests return 401.
package com.bank.controller;
import com.bank.dto.AccountDTO;
import com.bank.service.AccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import java.math.BigDecimal;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(AccountController.class)
class AccountControllerSecurityTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private AccountService accountService;
@Test
void shouldReturn401WhenNotAuthenticated() throws Exception {
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(username = "rajesh", roles = "CUSTOMER")
void shouldReturn200WhenAuthenticated() throws Exception {
AccountDTO account = new AccountDTO(
"SAV2001", "Rajesh Kumar",
new BigDecimal("75000.00"), "ACTIVE");
when(accountService.findAccount("SAV2001")).thenReturn(account);
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accountId").value("SAV2001"));
}
@Test
@WithMockUser(username = "rajesh", roles = "CUSTOMER")
void shouldReturn403WhenRoleInsufficient() throws Exception {
// /api/accounts/admin endpoint requires ADMIN role
mockMvc.perform(get("/api/accounts/admin/audit-log"))
.andExpect(status().isForbidden());
}
}
Test output:
shouldReturn401WhenNotAuthenticated() PASSED
shouldReturn200WhenAuthenticated() PASSED
shouldReturn403WhenRoleInsufficient() PASSED
What should a senior or principal engineer know?
- Test naming convention. Use descriptive names like shouldReturn404WhenAccountNotFound instead of test1. The test name is the documentation of the expected behavior. When a test fails in CI, the name tells you what broke without reading the test code.
- MockMvc result actions for debugging. Use .andDo(print()) during development to see the full request and response. Remove it before committing.
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
mockMvc.perform(get("/api/accounts/SAV2001"))
.andDo(print()) // prints full request/response to stdout
.andExpect(status().isOk());
- Test context caching. Spring caches the application context across test classes that use the same configuration. If all your @WebMvcTest classes test different controllers, each one creates a separate context. Group tests that share the same controller in the same class to maximize cache reuse.
- Custom argument resolvers and filters. @WebMvcTest loads all @Component-annotated filters and argument resolvers. If your CorrelationIdFilter or a custom AuthenticationArgumentResolver depends on a service bean, you need to mock that dependency too.
- AssertJ and Hamcrest. MockMvc uses Hamcrest matchers by default. For more readable assertions, you can extract the response body as a string and use AssertJ:
String json = mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
assertThat(json).contains("SAV2001");
assertThat(json).contains("Rajesh Kumar");
- MockMvc with Spring Boot 3.4+ and @MockitoBean. Spring Boot 3.4 introduced @MockitoBean and @SpyBean annotations in the org.springframework.test.context.bean.override.mockito package, replacing the deprecated org.springframework.boot.test.mock.mockito versions. The new annotations work identically but are part of the Spring Framework rather than Spring Boot.
What are common interview follow-up questions?
- What is the difference between @WebMvcTest and @SpringBootTest with @AutoConfigureMockMvc?
- How do you test file upload endpoints with MockMvc?
- How do you test pagination and sorting with MockMvc?
- What is @MockitoBean and how is it different from @MockBean?
- How do you test exception handlers with MockMvc?
- How do you test endpoints that require JWT authentication?
- What is the difference between MockMvc and WebTestClient?
- How do you avoid loading the full context in controller tests?
Visual Overview
MockMvc Request Processing (no real server)
=============================================
Test Method
│
│ mockMvc.perform(get("/api/accounts/SAV2001"))
▼
┌──────────────────────────────────────────────┐
│ MockMvc (in-memory, no Tomcat) │
│ │
│ 1. DispatcherServlet │
│ Routes /api/accounts/{id} to controller │
│ │
│ 2. Filters (CorrelationIdFilter, Security) │
│ Run exactly as in production │
│ │
│ 3. AccountController.getAccount("SAV2001") │
│ Calls accountService.findAccount() │
│ (accountService is a Mockito mock) │
│ │
│ 4. Jackson serializes AccountDTO to JSON │
│ │
│ 5. Response: 200 OK, application/json │
│ {"accountId":"SAV2001",...} │
└──────────────────────────────────────────────┘
│
▼
ResultActions
│
├── .andExpect(status().isOk())
├── .andExpect(jsonPath("$.accountId").value("SAV2001"))
└── .andExpect(jsonPath("$.balance").value(75000.00))
@WebMvcTest vs @SpringBootTest Bean Loading ============================================= @WebMvcTest(AccountController.class) ┌──────────────────────────────────────┐ │ Loaded: │ │ AccountController │ │ GlobalExceptionHandler │ │ CorrelationIdFilter │ │ Jackson converters │ │ @MockitoBean AccountService │ │ │ │ NOT loaded: │ │ AccountServiceImpl │ │ AccountRepository │ │ DataSource / JPA / Flyway │ │ KafkaTemplate / RedisTemplate │ └──────────────────────────────────────┘ Startup: ~1.5 seconds @SpringBootTest ┌──────────────────────────────────────┐ │ Loaded: EVERYTHING │ │ All controllers │ │ All services │ │ All repositories │ │ DataSource + JPA + Flyway │ │ Kafka + Redis + Cache │ │ Embedded Tomcat (optional) │ └──────────────────────────────────────┘ Startup: ~12 seconds
Key Takeaway
MockMvc is the standard tool for testing Spring Boot REST controllers without starting a real server. It processes HTTP requests through the full Spring MVC pipeline in memory: dispatcher servlet, filters, argument resolvers, validation, controller methods, exception handlers, and JSON serialization. The test verifies that your controller correctly maps URLs, validates input, calls the right service method, and returns the right HTTP status and JSON structure.
@WebMvcTest is the test slice annotation that makes MockMvc tests fast. It loads only the web layer: your controller, exception handlers, filters, and converters. Services and repositories are not loaded, so you replace them with @MockitoBean mocks. This keeps the test context startup under 2 seconds compared to 10 to 30 seconds for a full @SpringBootTest.
A complete MockMvc test suite for a banking AccountController covers the success path (200 with correct JSON), validation errors (400 when holder name is blank or deposit is negative), not-found errors (404 when the account does not exist), and authorization (401 without credentials, 403 without the right role). Each scenario is a separate test method with a descriptive name that documents the expected behavior.
The most common mistake is using @SpringBootTest with @AutoConfigureMockMvc when @WebMvcTest is sufficient. This loads the entire application context including the database, message brokers, and caches, making tests slow and fragile. Reserve @SpringBootTest for end-to-end integration tests that verify the complete request flow from controller to database.
Remember one sentence: use @WebMvcTest for fast, isolated controller tests with mocked services, and reserve @SpringBootTest for full integration tests.
---