@WebMvcTest helps test only the web layer of your application, like controllers, without starting the full app. It makes tests faster and focused.
@WebMvcTest for controller testing in JUnit
@WebMvcTest(ControllerClass.class) public class ControllerTest { @Autowired private MockMvc mockMvc; @MockBean private SomeService someService; @Test public void testControllerMethod() throws Exception { mockMvc.perform(get("/endpoint")) .andExpect(status().isOk()) .andExpect(content().string("expected response")); } }
@WebMvcTest loads only the controller and related MVC components, not the full Spring context.
Use @MockBean to provide mock implementations for service dependencies.
@WebMvcTest(HelloController.class) public class HelloControllerTest { @Autowired private MockMvc mockMvc; @Test public void shouldReturnHello() throws Exception { mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello World")); } }
@WebMvcTest(UserController.class) public class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test public void shouldReturnUserName() throws Exception { when(userService.getUserName()).thenReturn("Alice"); mockMvc.perform(get("/username")) .andExpect(status().isOk()) .andExpect(content().string("Alice")); } }
This test checks the /greet endpoint of GreetingController. The GreetingService is mocked to return "Hello Test". The test verifies the HTTP status is 200 OK and the response body matches the mocked string.
package com.example.demo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.mockito.Mockito.when; 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.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; @WebMvcTest(GreetingController.class) public class GreetingControllerTest { @Autowired private MockMvc mockMvc; @MockBean private GreetingService greetingService; @Test public void testGreeting() throws Exception { when(greetingService.greet()).thenReturn("Hello Test"); mockMvc.perform(get("/greet")) .andExpect(status().isOk()) .andExpect(content().string("Hello Test")); } } // Controller class package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { private final GreetingService greetingService; public GreetingController(GreetingService greetingService) { this.greetingService = greetingService; } @GetMapping("/greet") public String greet() { return greetingService.greet(); } } // Service interface package com.example.demo; public interface GreetingService { String greet(); }
Always mock service dependencies to keep controller tests isolated.
Use MockMvc to simulate HTTP requests and check responses without starting a server.
@WebMvcTest does not load security or database layers unless explicitly configured.
@WebMvcTest focuses on testing Spring MVC controllers only.
MockMvc helps simulate HTTP calls and verify responses.
Mock dependencies with @MockBean to isolate controller logic.
Practice
@WebMvcTest in Spring Boot testing?Solution
Step 1: Understand the role of @WebMvcTest
@WebMvcTest is designed to load only the Spring MVC components, mainly controllers, for focused testing.Step 2: Compare with other test types
Unlike full integration tests, it does not load services or repositories, making tests faster and isolated.Final Answer:
To test only the Spring MVC controllers without starting the full application context -> Option AQuick Check:
@WebMvcTest = Controller-only test [OK]
- Thinking @WebMvcTest loads full application context
- Confusing @WebMvcTest with @SpringBootTest
- Assuming it mocks external APIs automatically
@WebMvcTest annotated test class?Solution
Step 1: Identify mocking annotation for Spring beans
@MockBean is used to add mock implementations of Spring beans into the application context during tests.Step 2: Differentiate from other annotations
@MockMvc is not an annotation, @Autowired injects real beans, and @InjectMocks is from Mockito but not for Spring context injection.Final Answer:
@MockBean -> Option DQuick Check:
Mock dependencies in @WebMvcTest = @MockBean [OK]
- Using @Autowired instead of @MockBean for mocks
- Confusing @MockBean with Mockito's @InjectMocks
- Thinking @MockMvc is an annotation
@WebMvcTest and MockMvc:
@WebMvcTest(MyController.class)
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testHello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello World"));
}
}
What will happen if the controller method mapped to /hello returns "Hello World" as response?Solution
Step 1: Analyze the test expectations
The test expects HTTP status 200 OK and response body "Hello World".Step 2: Match with controller behavior
If the controller returns "Hello World" with status 200, both expectations are met, so the test passes.Final Answer:
The test will pass because the response matches the expected string -> Option BQuick Check:
Matching response and status = test pass [OK]
- Assuming test fails if no explicit status set in controller
- Confusing autowiring issues with test failures
- Ignoring response content in assertions
@WebMvcTest(MyController.class)
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MyService myService;
@Test
void testEndpoint() throws Exception {
when(myService.getData()).thenReturn("data");
mockMvc.perform(get("/data"))
.andExpect(status().isOk())
.andExpect(content().string("data"));
}
}
If the test fails with a 404 Not Found error, what is the most likely cause?Solution
Step 1: Understand 404 error in MockMvc test
A 404 means the requested URL is not found in the controller mappings.Step 2: Check test setup
@WebMvcTest loads only controllers; if /data mapping is missing or incorrect, 404 occurs despite mocks.Final Answer:
The controller method for /data is missing or not mapped correctly -> Option CQuick Check:
404 error = missing controller mapping [OK]
- Blaming mock service return value for 404
- Assuming @SpringBootTest is needed for controller tests
- Ignoring URL mapping correctness
@WebMvcTest, how should you mock the service and verify the controller returns JSON with the user list correctly?Solution
Step 1: Mock the service dependency with @MockBean
In @WebMvcTest, use @MockBean to replace the service bean with a mock and stub its method to return the user list.Step 2: Use MockMvc to perform HTTP GET and verify JSON response
Perform a GET request on the controller endpoint and assert the JSON response matches the expected user list.Final Answer:
Use @MockBean to mock the service, stub the method to return a list, then use MockMvc to perform GET and expect JSON content -> Option AQuick Check:
Mock service + MockMvc GET + JSON assert = correct test [OK]
- Injecting real service instead of mocking
- Using full context test instead of @WebMvcTest
- Calling controller methods directly without MockMvc
Ready to prove it?
Pass the test and this pattern moves unknown
