Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

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:

  1. Annotate test class with @WebMvcTest.
  2. 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.