Tartalomjegyzék

< JUnit5

JUnit5 - metódusok 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

src/App.java
public class App {    
    public static void main(String[] args) throws Exception {
        Rhombus rhombus = new Rhombus();
        rhombus.calcPerimeter();
    }
}
src/Rhombus.java
public class Rhombus {
    public double calcPerimeter() {
        return 0;
    }
    public double calcArea() {
        return 0;
    }
}
test/RhombusTest.java
import static org.junit.jupiter.api.Assertions.assertTrue;
 
import java.lang.reflect.Method;
import java.util.ArrayList;
 
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
 
public class RhombusTest {
    ArrayList<String> rhombusMethodList;
    @BeforeEach
    void getMethodList() {
        this.rhombusMethodList = new ArrayList<>();
        Method[] methods = Rhombus.class.getDeclaredMethods();
        for(Method method : methods) {
            this.rhombusMethodList.add(method.getName());
        }        
    }
    @Test
    void testCalcPerimter() {        
            boolean hasCalcPerimeter = rhombusMethodList.contains("calcPerimeter");
            assertTrue(hasCalcPerimeter);
    }
    @Test
    void testCalcArea() {        
            boolean hasCalcArea = rhombusMethodList.contains("calcArea");
            assertTrue(hasCalcArea);
    }
}

Metódus visszatérési értékének tesztje

test/TombsugTest.java
import static org.junit.jupiter.api.Assertions.assertTrue;
 
import java.lang.reflect.Method;
 
import org.junit.Before;
import org.junit.Test;
 
public class TombsugTest {
    Tombsug tombsug;
    @Before
    public void setUp() {
        this.tombsug = new Tombsug();
    }
    @Test
    public void testInput()  {
        boolean ok = false;
        try {
            Method inputMethod = Tombsug.class.getMethod("input", String.class);    
            if("java.lang.String".equals(inputMethod.getReturnType().getName())) {
                ok = true;
            }
        } catch (NoSuchMethodException e) {
            System.out.println("Hiba! Nincs ilyen metódus!");
        }
        assertTrue(ok, "Hiba! Nem létezik a input(String msg) metódus!");
    }
}