0
0
Spring Bootframework~30 mins

MockMvc for HTTP assertions in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
MockMvc for HTTP assertions
📖 Scenario: You are building a simple Spring Boot web application that has a REST endpoint to greet users by name.To ensure your endpoint works correctly, you want to write tests that simulate HTTP requests and check the responses without starting the full server.
🎯 Goal: Create a test class using MockMvc to send a GET request to the greeting endpoint and assert the HTTP status and response content.
📋 What You'll Learn
Create a Spring Boot REST controller with a GET endpoint /greet that accepts a name query parameter and returns a greeting message.
Set up a MockMvc instance in the test class.
Write a test method that performs a GET request to /greet?name=Alice using MockMvc.
Assert that the HTTP status is 200 (OK) and the response body contains the greeting message Hello, Alice!.
💡 Why This Matters
🌍 Real World
MockMvc is used in Spring Boot projects to test web controllers quickly and reliably without deploying the full application server.
💼 Career
Understanding MockMvc is essential for backend developers working with Spring Boot to write automated tests that ensure web endpoints behave as expected.
Progress0 / 4 steps
1
Create the GreetingController REST endpoint
Create a Spring Boot REST controller class called GreetingController with a GET mapping for /greet that accepts a name query parameter and returns the string "Hello, " + name + "!".
Spring Boot
Need a hint?

Use @RestController and @GetMapping annotations. The method should take a @RequestParam String name and return the greeting string.

2
Set up MockMvc in the test class
Create a test class called GreetingControllerTest annotated with @WebMvcTest(GreetingController.class). Inject a MockMvc field using @Autowired.
Spring Boot
Need a hint?

Use @WebMvcTest on the test class and @Autowired to inject MockMvc.

3
Write a test method to perform GET request and assert response
In GreetingControllerTest, write a test method called testGreetReturnsHelloMessage annotated with @Test. Use mockMvc.perform to send a GET request to /greet?name=Alice. Assert that the status is 200 and the response content is exactly Hello, Alice!.
Spring Boot
Need a hint?

Use mockMvc.perform(get(...)) and chain andExpect calls for status and content.

4
Add @AutoConfigureMockMvc annotation to enable MockMvc auto-configuration
In the GreetingControllerTest class, add the annotation @AutoConfigureMockMvc above the class declaration to enable automatic MockMvc configuration.
Spring Boot
Need a hint?

Add @AutoConfigureMockMvc above the test class to enable MockMvc auto-configuration.