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.
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.
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!"; // } // }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Spring context loads only the HelloController and related MVC components | Spring Boot test context initialized with HelloController bean and MockMvc configured | - | PASS |
| 2 | MockMvc performs a GET request to '/hello' endpoint | Mock HTTP request sent to HelloController's /hello mapping | - | PASS |
| 3 | Check that HTTP response status is 200 OK | Response received from controller with status code 200 | Assert response status is 200 | PASS |
| 4 | Check that response body content equals 'Hello, World!' | Response body contains the string 'Hello, World!' | Assert response content string equals 'Hello, World!' | PASS |
| 5 | Test completes successfully | Test context remains stable, no errors thrown | - | PASS |