Tartalomjegyzék

< JUnit5

JUnit5 - osztály tesztelése

VSCode beállítása

.vscode/settings.json
{
    "java.project.sourcePaths": ["src", "test"],
    "java.project.outputPath": "bin",
    "java.project.referencedLibraries": [
        "lib/**/*.jar",
        "c:\\Users\\janos\\Library\\junit\\junit-jupiter-api-5.9.1.jar",
        "c:\\Users\\janos\\Library\\junit\\junit-platform-console-standalone-1.9.1.jar",        
        "/home/janos/Library/junit/junit-jupiter-api-5.9.1.jar",
        "/home/janos/Library/junit/junit-platform-console-standalone-1.9.1.jar"
    ]  
}

Minta

A példaprogramban metódus tesztelés is van.

src/App.java
public class App {    
    public static void main(String[] args) throws Exception {
        new MainController();
    }
}
src/models/FileHandler.java
import java.util.ArrayList;
 
public class FileHandler {
    ArrayList<String> wordList;
    public void readFile() {
 
    }
}
test/SzotarTest.java
import static org.junit.jupiter.api.Assertions.assertTrue;
 
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
 
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
 
import models.FileHandler;
 
public class SzotarTest {
    ArrayList<String> methodNameList;
    ArrayList<String> fieldNameList;
    @BeforeEach
    void setMethodList() {
        this.methodNameList = new ArrayList<>();
        Method[] methods = FileHandler.class.getDeclaredMethods();
        for(Method method : methods) {
            this.methodNameList.add(method.getName());
        }
    }
    @BeforeEach
    void setFieldList() {
        this.fieldNameList = new ArrayList<>();
        Field[] fields = FileHandler.class.getDeclaredFields();
        for(Field field: fields) {
            this.fieldNameList.add(field.getName());
        }
    }
    @Test
    void checkReadFileMethod() {
        boolean hasReadFileMethod = this.methodNameList.contains("readFile");
        assertTrue(hasReadFileMethod);
    }
    @Test
    void checkWordField() {
        boolean hasWordField = this.fieldNameList.contains("wordList");
        assertTrue(hasWordField);
    }
    boolean existsClass(String className) {
        try {
            Class.forName(className);
            return true;
        }catch(ClassNotFoundException e) {
            return false;
        }
    }
    @Test
    void checkClass() {
        boolean hasClassFileHandler = existsClass("models.FileHandler");
        assertTrue(hasClassFileHandler);
    }
 
}