Junit5 動態執行測試類

Junit5 重新構造了junit5,支持在代碼中執行測試類

使用LauncherDiscoveryRequest、Launcher的方法實現

public void executeByJunit5(String serviceName, String branch, String fileName) {
        //需要執行的測試類絕對路徑
        String testCaseFileAbsPath = "/opt/testcases/" + fileName + ".class";
        // 被測服務當前branch dependencies lib目錄
        String branchLibPath = "/opt/libs/clustera-1-2-3";
        try {
            //新建classloader
            ClassLoader loader = ClassLoaderUtil.createClassLoader("/opt/common/lib");

            Collection<File> jars = FileUtils.listFiles(new File(branchLibPath), new String[]{"jar"}, true);
            for (File f : jars) {
                if (!f.getName().contains("sources")) {
                    String dependentJar = f.getCanonicalPath();
                    ClassLoaderUtil.addPath(loader, new File(dependentJar).toURI().toURL());
                }
            }
            // 測試類加到classloader上
            ClassLoaderUtil.addPath(loader, new File("/opt/testcases/").toURI().toURL());
            // 設置當前進程的classloader爲新建的loader
            Thread.currentThread().setContextClassLoader(loader);

            // 測試類
            Class testCaseClazz = loader.loadClass(fileName);

            LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder
                    .request()
                    .selectors(selectClass(testCaseClazz)).build();

            Launcher launcher = LauncherFactory.create();

            // Register a listener of your choice
            SummaryGeneratingListener listener = new SummaryGeneratingListener();
            launcher.registerTestExecutionListeners(listener);

            launcher.execute(request);

            TestExecutionSummary summary = listener.getSummary();

            // 報告看情況入庫還是直接展示
            loggerHelper.info(summary.toString());
        } catch (Exception e) {
            e.printStackTrace();
            loggerHelper.error(e.getStackTrace().toString());
        }
    }

對應的pom.xml

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.5.2</version>
</dependency>
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-runner</artifactId>
    <version>1.5.2</version>
</dependency>

使用EngineTestKit執行測試類

public void executeByJunit5(String serviceName, String branch, String fileName) {
        //需要執行的測試類絕對路徑
        String testCaseFileAbsPath = "/opt/testcases/" + fileName + ".class";
        // 被測服務當前branch dependencies lib目錄
        String branchLibPath = "/opt/libs/clustera-1-2-3";
        try {
            //新建classloader
            ClassLoader loader = ClassLoaderUtil.createClassLoader("/opt/common/lib");

            Collection<File> jars = FileUtils.listFiles(new File(branchLibPath), new String[]{"jar"}, true);
            for (File f : jars) {
                if (!f.getName().contains("sources")) {
                    String dependentJar = f.getCanonicalPath();
                    ClassLoaderUtil.addPath(loader, new File(dependentJar).toURI().toURL());
                }
            }
            // 測試類加到classloader上
            ClassLoaderUtil.addPath(loader, new File("/opt/testcases/").toURI().toURL());
            // 設置當前進程的classloader爲新建的loader
            Thread.currentThread().setContextClassLoader(loader);

            // 測試類
            Class testCaseClazz = loader.loadClass(fileName);

            // 這種方法不會生成報告
            EngineTestKit
                    .engine("junit-jupiter")
                    .selectors(selectClass(testCaseClazz))
                    .execute();
        } catch (Exception e) {
            e.printStackTrace();
            loggerHelper.error(e.getStackTrace().toString());
        }
    }

pom.xml除了上面的依賴外,還需要增加

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-testkit</artifactId>
    <version>1.5.1</version>
</dependency>

Q&A

Q: 如果在編譯測“警告: 未知的枚舉常量 Status.STABLE 原因: 找不到org.apiguardian.api.API$Status的類文件”
A: claspath中缺少 apiguardian-api-1.1.0.jar

參考資料:
JUnit 5 User Guide https://goodjob.n2sm.net/cache/?docId=61b8421cac86430996e043365854d253&hq=Java
Junit5學習筆記 https://vitzhou.gitbooks.io/junit5/junit/advanced_topics.html
JUnit 5 Maven Dependency https://howtodoinjava.com/junit5/junit5-maven-dependency/
6.1.1. Discovering Tests https://junit.org/junit5/docs/current/user-guide/#launcher-api-discovery

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章