Spring Boot FAQ: Top Questions
47. How do you test Spring Boot controllers?
You can test Spring Boot controllers using @WebMvcTest
along with MockMvc
to simulate HTTP requests.
πΊοΈ Steps:
- Annotate test class with
@WebMvcTest
. - Use
MockMvc
to perform requests and assert results.
π₯ Example:
@WebMvcTest(HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnGreeting() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Spring Boot!"));
}
}
π Expected Output:
Test passes if endpoint returns correct response.
π οΈ Use Cases:
- Testing REST API endpoints in isolation.
- Validating response format and HTTP status.