如何以编程方式运行 JUnit 测试

问题描述 投票:0回答:1

我有以下代码,我正在尝试自动执行两个项目下的特定测试用例。但执行后似乎大部分测试结果都是错误的。我怀疑这可能是由于缺少依赖项造成的。有人可以帮我检查和修改吗?

public class TestRunner {
    public static void main(String[] args) throws Exception {
        TestExecutionSummary summary1= runSingleTest("E:\\Tutorial\\proj1\\target\\test-classes","test.CFGTestTest");
        TestExecutionSummary summary2= runSingleTest("E:\\Tutorial\\proj2\\target\\test-classes","test.ConfigTest");
        CompareTestResult(summary1,summary2);
    }

    public  static void CompareTestResult(TestExecutionSummary summary1,TestExecutionSummary summary2){
        System.out.println("\n-----------------Compare Test Result-----------------");
        if(summary1.getTestsSucceededCount()==summary2.getTestsSucceededCount()){
            System.out.println("Test1 and Test2 are the same");
            System.out.println("Passed: "+summary1.getTestsSucceededCount()+" Failed: "+summary1.getTestsFailedCount());
        }else{
            System.out.println("Test1 and Test2 are different");
            System.out.println("Test1: "+"Passed: "+summary1.getTestsSucceededCount()+" Failed: "+summary1.getTestsFailedCount());
            System.out.println("Test2: "+"Passed: "+summary2.getTestsSucceededCount()+" Failed: "+summary2.getTestsFailedCount());
        }
        System.out.println("-----------------------------------------------------\n");
    }

    /**
     * Execute a single test.
     * @param classPath The classpath
     * @param className The class name
     * @throws Exception Exceptions
     */
    private static TestExecutionSummary runSingleTest(String classPath,String className) throws Exception {
        Class<?> testClass = getTestClassFromPath(classPath, className);
        assert testClass != null;
        return runTest(testClass);
    }

    /**
     * Get the test class from the classpath and class name.
     * @param classPath The classpath
     * @param className The class name eg: com.example.Test
     * @return The test class
     * @throws Exception Exceptions
     */
    private static Class<?> getTestClassFromPath(String classPath,String className) throws Exception {
        // Check if the path exists
        File file = new File(classPath);
        if (!file.exists()) {
            System.out.println("Path does not exist");
            return null;
        }
        URL url = file.toURI().toURL();
        try (URLClassLoader classLoader = new URLClassLoader(new URL[]{url})) {
            return classLoader.loadClass(className);
        }catch (ClassNotFoundException e){
            System.out.println("Class loading failed"+e.getMessage());
            throw e;
        }catch (Exception e){
            System.out.println("Exception"+e.getMessage());
            throw e;
        }
    }

    /**
     * Run the test.
     * @param testClass The test class
     */
    private static TestExecutionSummary runTest(Class<?> testClass) {
        System.out.println("Running tests for class " + testClass.getName());
        Launcher launcher = LauncherFactory.create(); // Create a Launcher
        // Create a SummaryGeneratingListener
        SummaryGeneratingListener listener = new SummaryGeneratingListener();

        // Create a LauncherDiscoveryRequest that includes the test class
        LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                .selectors(selectClass(testClass))
                .build();

        // Register the listener with the Launcher
        launcher.registerTestExecutionListeners(listener);
        launcher.execute(request); // Execute the tests

        // Get the execute summary
        return listener.getSummary();
    }
}

-----------------测试结果对比----------------- 测试1和测试2不同 测试1:通过:0 失败:5 测试2:通过:0 失败:2

java unit-testing
1个回答
0
投票

将以下依赖项添加到您的项目中:

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.9.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <version>1.2.0</version>
    </dependency>
</dependencies>

然后添加测试:

public class FirstUnitTest {
    @Test
    public void whenThis_thenThat() {
        // TODO some logic
        assertTrue(true);
    }

    @Test
    public void whenSomething_thenSomething() {
        // TODO some logic
        assertTrue(true);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.