Create the ControllerTests.java File
In this step, you will learn how to create the ControllerTests.java
file to test the StudentController
class using the Mockito testing framework.
- Open your IDE and navigate to the
/test/java/org/labex/springboottesting
directory in your project.
- Create a new Java file named
ControllerTests.java
.
- In the
ControllerTests.java
file, add the following code:
package org.labex.springboottesting;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.labex.springboottesting.dao.IStudentDAO;
import org.labex.springboottesting.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import java.util.ArrayList;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest // Loading the Spring Boot application context.
@EnableWebMvc // Enables Spring Web MVC features.
@AutoConfigureMockMvc // Configures the MockMvc instance.
class ControllerTests {
@Autowired
private MockMvc mockMvc; // Autowires the MockMvc instance for simulating HTTP requests.
private ObjectMapper objectMapper; // ObjectMapper for JSON conversion.
@MockBean // MockBean annotation to create a mock for IStudentDAO.
private IStudentDAO studentDAO;
@BeforeEach
void setUp() {
// Initializing ObjectMapper to convert objects to JSON and vice versa.
this.objectMapper = new ObjectMapper();
}
@Test
void testGetStudents() throws Exception {
// Creating sample students.
Student s1 = new Student("20191001", "John", 18, "Male");
Student s2 = new Student("20191069", "Lily", 19, "Female");
// Creating a list of students and adding sample students to it.
ArrayList<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
// Mocking the behavior of studentDAO to return the list of students when findStudentAll() is called.
when(studentDAO.findStudentAll()).thenReturn(list);
// Performing a GET request to retrieve all students and validating the response.
this.mockMvc.perform(get("/api/v2/students")
.accept("application/json; charset=UTF-8")) // Sets the accept header to specify the expected response type.
.andDo(print()) // Prints request and response details.
.andExpect(status().isOk()) // Verifies that the response status is OK (200).
.andReturn(); // Returns the MvcResult object for further assertions.
}
@Test
void testGetStudent() throws Exception {
// Creating a sample student.
Student s1 = new Student("20191001", "John", 18, "Male");
// Mocking the behavior of studentDAO to return the sample student when findStudentById() is called with "20191001".
when(studentDAO.findStudentById("20191001")).thenReturn(s1);
// Performing a GET request to retrieve a specific student by ID and validating the response.
this.mockMvc.perform(get("/api/v2/student/20191001")
.accept("application/json; charset=UTF-8"))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
@Test
void testModifyStudent() throws Exception {
// Creating a sample student.
Student s1 = new Student("20191001", "John", 18, "Male");
// Converting the sample student to JSON format.
String content = objectMapper.writeValueAsString(s1);
// Mocking the behavior of studentDAO to return true when updateStudent() is called with any student object.
when(studentDAO.updateStudent(any())).thenReturn(true);
// Performing a PUT request to modify a student and validating the response.
this.mockMvc.perform(put("/api/v2/student")
.content(content)
.contentType(MediaType.APPLICATION_JSON)
.accept("application/json; charset=UTF-8"))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
}
The ControllerTests
class is annotated with @SpringBootTest
to load the Spring Boot application context, @EnableWebMvc
to enable Spring Web MVC features, and @AutoConfigureMockMvc
to configure the MockMvc
instance. The class contains three test methods:
testGetStudents()
: Tests the getStudents()
method of the StudentController
class by mocking the behavior of the IStudentDAO
interface and performing a GET request to the /api/v2/students
endpoint.
testGetStudent()
: Tests the getStudent()
method of the StudentController
class by mocking the behavior of the IStudentDAO
interface and performing a GET request to the /api/v2/student/20191001
endpoint.
testModifyStudent()
: Tests the modifyStudent()
method of the StudentController
class by mocking the behavior of the IStudentDAO
interface, converting a sample student object to JSON, and performing a PUT request to the /api/v2/student
endpoint.