JUnit — написание примеров тестовых случаев для StudentService на Java

Опубликовано: 24 Февраля, 2023

Во многих частях проектов коллекции играют главную роль. Среди них ArrayList — удобная для пользователя коллекция, которая много раз потребуется для разработки программного обеспечения. Возьмем пример проекта, который включает модель «Студент», которая содержит такие атрибуты, как studentId, studentName, CourseName и GPA. Давайте добавим несколько сервисов, таких как добавление/вставка/фильтрация по курсу/фильтрация по gpa/удаление, и в любой момент времени доступные данные должны быть проверены JUnit.

Пример проекта

Структура проекта:

Это проект maven. Следовательно, все зависимости должны быть указаны в

пом.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
  
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gfg.StudentServicesJava</groupId>
    <artifactId>StudentServicesJava</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
  
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>5.3.1</junit.version>
        <pitest.version>1.4.3</pitest.version>
    </properties>
  
    <dependencies>
  
        <!-- junit 5, unit test -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
  
    </dependencies>
    <build>
        <finalName>maven-mutation-testing</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M1</version>
            </plugin>
  
            <plugin>
                <groupId>org.pitest</groupId>
                <artifactId>pitest-maven</artifactId>
                <version>${pitest.version}</version>
  
                <executions>
                    <execution>
                        <id>pit-report</id>
                        <phase>test</phase>
                        <goals>
                            <goal>mutationCoverage</goal>
                        </goals>
                    </execution>
                </executions>
  
                <!-- https://github.com/hcoles/pitest/issues/284 -->
                <!-- Need this to support JUnit 5 -->
                <dependencies>
                    <dependency>
                        <groupId>org.pitest</groupId>
                        <artifactId>pitest-junit5-plugin</artifactId>
                        <version>0.8</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <targetClasses>
                        <param>com.gfg.StudentServicesJava.*StudentServicesJava*</param>
                    </targetClasses>
                    <targetTests>
                        <param>com.gfg.StudentServicesJava.*</param>
                    </targetTests>
                </configuration>
            </plugin>
  
        </plugins>
    </build>
  
</project>

Давайте начнем с класса «Студент» сейчас

Студент.java

Java




public class Student {
    public Student(String studentName, int studentId,
                   String courseName, double gpa)
    {
        super();
        this.studentName = studentName;
        this.studentId = studentId;
        this.courseName = courseName;
        this.gpa = gpa;
    }
    public Student()
    {
        // via setter methods, rest fields are done
    }
    String studentName;
    int studentId;
    String courseName;
    double gpa;
    public String getStudentName() { return studentName; }
    public void setStudentName(String studentName)
    {
        this.studentName = studentName;
    }
    public int getStudentId() { return studentId; }
    public void setStudentId(int studentId)
    {
        this.studentId = studentId;
    }
    public String getCourseName() { return courseName; }
    public void setCourseName(String courseName)
    {
        this.courseName = courseName;
    }
    public double getGpa() { return gpa; }
    public void setGpa(double gpa) { this.gpa = gpa; }
}

StudentServicesJava.java

Это в основном файл бизнес-логики. Об этом позаботятся следующие операции по обслуживанию студентов.

  • Добавление студентов в список и возврат размера списка студентов
  • Вставка учеников в середину списка и возврат размера списка учеников
  • Удаление студентов из списка и возврат размера списка студентов
  • Получение имени студента с помощью позиции индекса
  • Получение списка студентов по курсу
  • Получение списка учащихся gpawise

Java




import java.util.ArrayList;
import java.util.List;
  
public class StudentServicesJava {
      
    // Appending i.e. adding students at the end of the
    // list and returning the studentlist size
    public int appendStudent(Student student,List<Student> studentList) 
    {
        studentList.add(student);        
        return studentList.size();
    }
    
    // Inserting i.e. inserting students at the middle
    // of the list and returning the studentlist size
    public int insertStudent(Student student,List<Student> studentList,int index) 
    {
        studentList.add(index,student);        
        return studentList.size();
    }
    
    // Removing students from the list and 
    // returning the studentlist size
    public int removeStudent(List<Student> studentList,int index) 
    {
        studentList.remove(index);        
        return studentList.size();
    }
    
    // Returning the studentlist size
    public int getStudents(List<Student> studentList) {
        return studentList.size();
    }
    
    // Retrieving the student name at the specified index
    public String getStudentName(List<Student> studentList,int index) {
        return studentList.get(index).getStudentName();
    }
    
    // Returning the student list who matches for a specific course
    public List<Student> getStudentsByCourseWise(List<Student> studentList,String courseName) {
        List<Student> courseWiseStudents = new ArrayList<Student>();
        for (int i = 0; i < studentList.size(); i++) {
            if (studentList.get(i).getCourseName().equalsIgnoreCase(courseName)) {
                courseWiseStudents.add(studentList.get(i));
            }
        }
        return courseWiseStudents;
    }
    
    // Returning the student list who matches for a specific gpa and more
    public List<Student> getStudentsByGPA(List<Student> studentList,double gpa) {
        List<Student> gpaWiseStudents = new ArrayList<Student>();
        for (int i = 0; i < studentList.size(); i++) {
            if (studentList.get(i).getGpa() >= gpa) {
                gpaWiseStudents.add(studentList.get(i));
            }
        }
        return gpaWiseStudents;
    }
  
}

Всегда нужно проверять качество программного обеспечения с помощью тестирования JUNIT.

TestStudentServicesJava.java

Java




import static org.junit.jupiter.api.Assertions.assertEquals;
  
import java.util.ArrayList;
import java.util.List;
  
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
  
public class TestStudentServicesJava {
    List<Student> studentList = new ArrayList<Student>();
    StudentServicesJava studentServicesJavaObject = new StudentServicesJava();
  
    @DisplayName("Test check for adding/inserting/filtering by coursewise or gpawise/removing students ")
    @Test
    public void testCheckForAdditionAndDeletion() {
          
        assertEquals(true, studentServicesJavaObject.getStudents(studentList) == 0);
          
        // creating a student object
        Student student = new Student();
        student.setStudentId(1);
        student.setStudentName("Rachel");
        student.setCourseName("Java");
        student.setGpa(9.2);
        studentServicesJavaObject.appendStudent(student, studentList);
          
        // After appending the data
        assertEquals(true, studentServicesJavaObject.getStudents(studentList) == 1);
        Student monica = new Student("Monica", 2, "Java", 8.5);
        studentServicesJavaObject.insertStudent(monica, studentList, 0);
          
        // After inserting the data
        assertEquals(true, studentServicesJavaObject.getStudentName(studentList,0).equalsIgnoreCase("Monica"));
        assertEquals(true, studentServicesJavaObject.getStudents(studentList) == 2);
        Student phoebe = new Student("Phoebe", 3, "Python", 8.5);
        studentServicesJavaObject.appendStudent(phoebe, studentList);
        assertEquals(true, studentServicesJavaObject.getStudents(studentList) == 3);
        assertEquals(true, studentServicesJavaObject.getStudentName(studentList,1).equalsIgnoreCase("Rachel"));
        assertEquals(true, studentServicesJavaObject.getStudents(studentList) == studentList.size());
          
        // checking according to coursewise, first check for java
        List<Student> javaCourseWiseStudentList = new ArrayList<Student>();
        javaCourseWiseStudentList = studentServicesJavaObject.getStudentsByCourseWise(studentList, "java");
          
        // As for java, only 2 students are entered and checking like below
        assertEquals(true, studentServicesJavaObject.getStudents(javaCourseWiseStudentList) == 2);
        assertEquals(true, studentServicesJavaObject.getStudentName(javaCourseWiseStudentList,1).equalsIgnoreCase("Rachel"));
          
        List<Student> pythonCourseWiseStudentList = new ArrayList<Student>();
        pythonCourseWiseStudentList = studentServicesJavaObject.getStudentsByCourseWise(studentList, "python");
          
        // As for python, only 1 student is entered and checking like below
        assertEquals(true, studentServicesJavaObject.getStudents(pythonCourseWiseStudentList) == 1);
        assertEquals(true, studentServicesJavaObject.getStudentName(pythonCourseWiseStudentList,0).equalsIgnoreCase("phoebe"));
          
        // php course check
        List<Student> phpCourseWiseStudentList = new ArrayList<Student>();
        phpCourseWiseStudentList = studentServicesJavaObject.getStudentsByCourseWise(studentList, "unknown");
          
        // As for php, no stuents are there, we need to check like below
        assertEquals(true, studentServicesJavaObject.getStudents(phpCourseWiseStudentList) == 0);
          
        // Now with gpa check
        List<Student> gpaWiseStudentList = new ArrayList<Student>();