Student Management Module Unit Testing

JavaJavaBeginner
Practice Now

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.java file to test the StudentServiceImpl class using JUnit 5
  • How to create a ControllerTests.java file to test the StudentController class using JUnit 5 and Mockito
  • How to use Spring Boot testing features, such as @SpringBootTest and @MockBean, to load the necessary components and create mocks for testing
  • How to write test cases to verify the functionality of the queryStudents(), insertStudent(), and deleteStudent() methods in the StudentServiceImpl class
  • How to write test cases to verify the functionality of the getStudents(), getStudent(), and modifyStudent() methods in the StudentController class

🏆 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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/ConcurrentandNetworkProgrammingGroup(["`Concurrent and Network Programming`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/annotation("`Annotation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ConcurrentandNetworkProgrammingGroup -.-> java/working("`Working`") subgraph Lab Skills java/annotation -.-> lab-300404{{"`Student Management Module Unit Testing`"}} java/classes_objects -.-> lab-300404{{"`Student Management Module Unit Testing`"}} java/working -.-> lab-300404{{"`Student Management Module Unit Testing`"}} end

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.

  1. Open your IDE and navigate to the /test/java/org/labex/springboottesting directory in your project.
  2. Create a new Java file named ServiceTests.java.
  3. In the ServiceTests.java file, 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:

  1. testQueryStudents(): Tests the queryStudents() method of the IStudentService interface to ensure that the returned list of students has the expected size.
  2. testInsertStudent(): Tests the insertStudent() method of the IStudentService interface to ensure that the student insertion operation is successful.
  3. testDeleteStudent(): Tests the deleteStudent() method of the IStudentService interface 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.

  1. Open your IDE and navigate to the /test/java/org/labex/springboottesting directory in your project.
  2. Create a new Java file named ControllerTests.java.
  3. 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:

  1. 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.
  2. 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.
  3. 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.

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.

  1. Open a terminal or command prompt and navigate to your project directory using the following command:
cd ~/project/springboottesting/
  1. Run the following command to execute the ServiceTests class:
mvn test -Dtest=ServiceTests

This will run the three test methods in the ServiceTests class and display the results.

  1. Run the following command to execute the ControllerTests class:
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.

Other Java Tutorials you may like