Hackforge Academy

Category: java

what is junit

Published on 16 Jul 2026

Explanation

JUnit is the standard testing framework for Java applications, while MockMvc is a Spring testing utility that allows developers to test REST APIs without starting a real web server.

Code:

@SpringBootTest
@AutoConfigureMockMvc
class StudentControllerTest {

}

Explanation

Inject the MockMvc object into the test class. It simulates HTTP requests and verifies responses from REST controllers.

Code:

@Autowired
private MockMvc mockMvc;

Explanation

Use MockMvc to test GET endpoints. The perform() method sends a request, and expect() verifies the HTTP status and response.

Code:

@Test
void testGetStudents() throws Exception {
    mockMvc.perform(get("/students"))
            .andExpect(status().isOk());
}

Explanation

Verify JSON response values using jsonPath(). This ensures the API returns the expected data structure and values.

Code:

@Test
void testGetStudent() throws Exception {
    mockMvc.perform(get("/students/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("John"));
}

Explanation

Test POST endpoints by sending JSON data in the request body. Verify that the API returns the expected HTTP status code, such as 201 Created.

Code:

String json = "{\"name\":\"John\",\"email\":\"john@gmail.com\"}";

mockMvc.perform(post("/students")
        .contentType(MediaType.APPLICATION_JSON)
        .content(json))
        .andExpect(status().isCreated());

๐Ÿš€ 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