0
0
JUnittesting~10 mins

@WebMvcTest for controller testing in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks a Spring MVC controller using @WebMvcTest. It verifies that a GET request to the controller returns the expected HTTP status and response content.

Test Code - JUnit 5 with Spring Boot Test
JUnit
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.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testHelloEndpoint() throws Exception {
        mockMvc.perform(get("/hello"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello, World!"));
    }
}

// Controller class for reference:
// @RestController
// public class HelloController {
//     @GetMapping("/hello")
//     public String hello() {
//         return "Hello, World!";
//     }
// }
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Spring context loads only the HelloController and related MVC componentsSpring Boot test context initialized with HelloController bean and MockMvc configured-PASS
2MockMvc performs a GET request to '/hello' endpointMock HTTP request sent to HelloController's /hello mapping-PASS
3Check that HTTP response status is 200 OKResponse received from controller with status code 200Assert response status is 200PASS
4Check that response body content equals 'Hello, World!'Response body contains the string 'Hello, World!'Assert response content string equals 'Hello, World!'PASS
5Test completes successfullyTest context remains stable, no errors thrown-PASS
Failure Scenario
Failing Condition: The controller does not return the expected string or the endpoint is missing
Execution Trace Quiz - 3 Questions
Test your understanding
What does @WebMvcTest do in this test?
ALoads only the web layer including the specified controller
BLoads the entire Spring Boot application context
CMocks the database layer for testing
DRuns the application on a real server
Key Result
Use @WebMvcTest to isolate controller tests from other layers. This makes tests faster and focused on web behavior only.