JUnit — написание примеров тестовых случаев для StudentService на Java
Во многих частях проектов коллекции играют главную роль. Среди них ArrayList — удобная для пользователя коллекция, которая много раз потребуется для разработки программного обеспечения. Возьмем пример проекта, который включает модель «Студент», которая содержит такие атрибуты, как studentId, studentName, CourseName и GPA. Давайте добавим несколько сервисов, таких как добавление/вставка/фильтрация по курсу/фильтрация по gpa/удаление, и в любой момент времени доступные данные должны быть проверены JUnit.
Пример проекта
Структура проекта:
Это проект maven. Следовательно, все зависимости должны быть указаны в
пом.xml
XML
| <?xmlversion="1.0"encoding="UTF-8"?>         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0      <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>                 <!-- 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
| publicclassStudent {    publicStudent(String studentName, intstudentId,                   String courseName, doublegpa)    {        super();        this.studentName = studentName;        this.studentId = studentId;        this.courseName = courseName;        this.gpa = gpa;    }    publicStudent()    {        // via setter methods, rest fields are done    }    String studentName;    intstudentId;    String courseName;    doublegpa;    publicString getStudentName() { returnstudentName; }    publicvoidsetStudentName(String studentName)    {        this.studentName = studentName;    }    publicintgetStudentId() { returnstudentId; }    publicvoidsetStudentId(intstudentId)    {        this.studentId = studentId;    }    publicString getCourseName() { returncourseName; }    publicvoidsetCourseName(String courseName)    {        this.courseName = courseName;    }    publicdoublegetGpa() { returngpa; }    publicvoidsetGpa(doublegpa) { this.gpa = gpa; }} | 
StudentServicesJava.java
Это в основном файл бизнес-логики. Об этом позаботятся следующие операции по обслуживанию студентов.
- Добавление студентов в список и возврат размера списка студентов
- Вставка учеников в середину списка и возврат размера списка учеников
- Удаление студентов из списка и возврат размера списка студентов
- Получение имени студента с помощью позиции индекса
- Получение списка студентов по курсу
- Получение списка учащихся gpawise
Java
| importjava.util.ArrayList;importjava.util.List; publicclassStudentServicesJava {         // Appending i.e. adding students at the end of the    // list and returning the studentlist size    publicintappendStudent(Student student,List<Student> studentList)     {        studentList.add(student);                returnstudentList.size();    }       // Inserting i.e. inserting students at the middle    // of the list and returning the studentlist size    publicintinsertStudent(Student student,List<Student> studentList,intindex)     {        studentList.add(index,student);                returnstudentList.size();    }       // Removing students from the list and     // returning the studentlist size    publicintremoveStudent(List<Student> studentList,intindex)     {        studentList.remove(index);                returnstudentList.size();    }       // Returning the studentlist size    publicintgetStudents(List<Student> studentList) {        returnstudentList.size();    }       // Retrieving the student name at the specified index    publicString getStudentName(List<Student> studentList,intindex) {        returnstudentList.get(index).getStudentName();    }       // Returning the student list who matches for a specific course    publicList<Student> getStudentsByCourseWise(List<Student> studentList,String courseName) {        List<Student> courseWiseStudents = newArrayList<Student>();        for(inti = 0; i < studentList.size(); i++) {            if(studentList.get(i).getCourseName().equalsIgnoreCase(courseName)) {                courseWiseStudents.add(studentList.get(i));            }        }        returncourseWiseStudents;    }       // Returning the student list who matches for a specific gpa and more    publicList<Student> getStudentsByGPA(List<Student> studentList,doublegpa) {        List<Student> gpaWiseStudents = newArrayList<Student>();        for(inti = 0; i < studentList.size(); i++) {            if(studentList.get(i).getGpa() >= gpa) {                gpaWiseStudents.add(studentList.get(i));            }        }        returngpaWiseStudents;    } } | 
Всегда нужно проверять качество программного обеспечения с помощью тестирования JUNIT.
TestStudentServicesJava.java
Java
| importstaticorg.junit.jupiter.api.Assertions.assertEquals; importjava.util.ArrayList;importjava.util.List; importorg.junit.jupiter.api.DisplayName;importorg.junit.jupiter.api.Test; publicclassTestStudentServicesJava {    List<Student> studentList = newArrayList<Student>();    StudentServicesJava studentServicesJavaObject = newStudentServicesJava();     @DisplayName("Test check for adding/inserting/filtering by coursewise or gpawise/removing students ")    @Test    publicvoidtestCheckForAdditionAndDeletion() {                 assertEquals(true, studentServicesJavaObject.getStudents(studentList) == 0);                 // creating a student object        Student student = newStudent();        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 = newStudent("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 = newStudent("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 = newArrayList<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 = newArrayList<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 = newArrayList<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 = newArrayList<Student>();РЕКОМЕНДУЕМЫЕ СТАТЬИ |