Hackforge Academy

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));

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community