Introduction
In this project, you will learn how to create unit tests for a Student Management Module using JUnit 5 and Mockito. The project includes two main tasks: creating tests for the StudentServiceImpl class and creating tests for the StudentController class.
🎯 Tasks
In this project, you will learn:
- How to create a
ServiceTests.javafile to test theStudentServiceImplclass using JUnit 5 - How to create a
ControllerTests.javafile to test theStudentControllerclass using JUnit 5 and Mockito - How to use Spring Boot testing features, such as
@SpringBootTestand@MockBean, to load the necessary components and create mocks for testing - How to write test cases to verify the functionality of the
queryStudents(),insertStudent(), anddeleteStudent()methods in theStudentServiceImplclass - How to write test cases to verify the functionality of the
getStudents(),getStudent(), andmodifyStudent()methods in theStudentControllerclass
🏆 Achievements
After completing this project, you will be able to:
- Set up unit testing for a Spring Boot application using JUnit 5 and Mockito
- Use Spring Boot testing features to load the necessary components and create mocks for testing
- Write effective test cases to ensure the correctness of the service and controller layer implementations
- Use assertions to verify the expected behavior of the tested methods
Create the ServiceTests.java File
In this step, you will learn how to create the ServiceTests.java file to test the StudentServiceImpl class using JUnit 5.
- Open your IDE and navigate to the
/test/java/org/labex/springboottestingdirectory in your project. - Create a new Java file named
ServiceTests.java. - In the
ServiceTests.javafile, add the following code:
package org.labex.springboottesting;
import org.junit.jupiter.api.Test;
import org.labex.springboottesting.service.StudentServiceImpl;
import org.labex.springboottesting.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest(classes = StudentServiceImpl.class)
class ServiceTests {
@Autowired
private StudentServiceImpl service;
@Test
void testQueryStudents() {
// Testing the queryStudents() method of the service to ensure correct data retrieval.
List<Student> result = service.queryStudents();
// Asserting that the size of the returned list matches the expected size.
assertEquals(3, result.size());
}
@Test
void testInsertStudent() {
// Creating a sample student object to insert.
Student student = new Student("1", "test", 18, "male");
// Testing the insertStudent() method of the service to ensure successful insertion.
Boolean result = service.insertStudent(student);
// Asserting that the insertion operation was successful.
assertTrue(result);
}
@Test
void testDeleteStudent() {
// Testing the deleteStudent() method of the service to ensure successful deletion.
Boolean result = service.deleteStudent("20191001");
// Asserting that the deletion operation was successful.
assertTrue(result);
}
}
The ServiceTests class is annotated with @SpringBootTest(classes = StudentServiceImpl.class) to load the StudentServiceImpl implementation class in the test class. The class contains three test methods:
testQueryStudents(): Tests thequeryStudents()method of theIStudentServiceinterface to ensure that the returned list of students has the expected size.testInsertStudent(): Tests theinsertStudent()method of theIStudentServiceinterface to ensure that the student insertion operation is successful.testDeleteStudent(): Tests thedeleteStudent()method of theIStudentServiceinterface to ensure that the student deletion operation is successful.
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/springboottestingdirectory in your project. - Create a new Java file named
ControllerTests.java. - In the
ControllerTests.javafile, 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 thegetStudents()method of theStudentControllerclass by mocking the behavior of theIStudentDAOinterface and performing a GET request to the/api/v2/studentsendpoint.testGetStudent(): Tests thegetStudent()method of theStudentControllerclass by mocking the behavior of theIStudentDAOinterface and performing a GET request to the/api/v2/student/20191001endpoint.testModifyStudent(): Tests themodifyStudent()method of theStudentControllerclass by mocking the behavior of theIStudentDAOinterface, converting a sample student object to JSON, and performing a PUT request to the/api/v2/studentendpoint.
Run the Tests
Now that you have created the ServiceTests.java and ControllerTests.java files, you can run the tests to verify the functionality of the StudentServiceImpl and StudentController classes.
- Open a terminal or command prompt and navigate to your project directory using the following command:
cd ~/project/springboottesting/
- Run the following command to execute the
ServiceTestsclass:
mvn test -Dtest=ServiceTests
This will run the three test methods in the ServiceTests class and display the results.
- Run the following command to execute the
ControllerTestsclass:
mvn test -Dtest=ControllerTests
This will run the three test methods in the ControllerTests class and display the results.
You should see the test results, including any passing or failing tests, in the console output.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



