Test GET /api/greeting endpoint in GreetingController
Preconditions (2)
✅ Expected Result: The GET /api/greeting request returns HTTP 200 with JSON {"message": "Hello, World!"}
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.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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; @WebMvcTest(GreetingController.class) public class GreetingControllerTest { @Autowired private MockMvc mockMvc; @Test void testGreetingEndpoint() throws Exception { mockMvc.perform(get("/api/greeting")) .andExpect(status().isOk()) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.message").value("Hello, World!")); } } // Assume GreetingController.java exists with @RestController and GET /api/greeting returning {"message":"Hello, World!"}
This test class uses @WebMvcTest to load only the GreetingController and related MVC components, making the test fast and focused.
The MockMvc object is injected to simulate HTTP requests without starting a server.
The test method testGreetingEndpoint sends a GET request to /api/greeting and asserts:
application/jsonmessage field with value Hello, World!This ensures the controller behaves as expected.
Now add data-driven testing to verify the greeting message changes based on a 'name' query parameter with 3 different names.
@WebMvcTest in Spring Boot testing?@WebMvcTest annotated test class?@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?@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?@WebMvcTest, how should you mock the service and verify the controller returns JSON with the user list correctly?Pass the test and this pattern moves unknown