Category: spring_boot
Testing REST APIs Using JUnit and MockMvc
Published on 08 Jul 2026
Explanation
JUnit is used for unit testing while MockMvc tests REST endpoints without starting the server.
Code:
@SpringBootTest
@AutoConfigureMockMvc
class StudentControllerTest{}
Explanation
Inject MockMvc into the test class.
Code:
@Autowired private MockMvc mockMvc;
Explanation
Test GET endpoints using MockMvc.
Code:
mockMvc.perform(get("/students"))
.andExpect(status().isOk());
Explanation
Verify JSON response values.
Code:
mockMvc.perform(get("/students/1"))
.andExpect(jsonPath("$.name").value("John"));
Explanation
Test POST APIs by sending JSON requests.
Code:
mockMvc.perform(post("/students")
.contentType(MediaType.APPLICATION_JSON)
.content(json));