You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot项目中JUnit5程序化测试运行失效问题解决

问题简述

我有一段可正常运行的JUnit5测试程序化执行脚本,但将其迁移至Spring Boot项目中运行时,脚本无法识别并执行测试。


问题详情

我编写了一段通过代码运行已编译JUnit5测试类的程序,代码如下:

public static void main(String[] args) throws Exception {
    //创建类加载器以加载CalculatorTest(JUnit5测试类)
    ClassLoader cl = new URLClassLoader(new URL[]{new File("/home/admin/test_folder").toURI().toURL()});
    //从test_folder中加载已编译的CalculatorTest类以启动JUnit5测试
    Class cls = cl.loadClass("CalculatorTest");
    //启动JUnit测试并打印测试结果
    System.out.println(runTest(cls));
}
public static List<String> runTest(Class clazz) {
    Launcher launcher = LauncherFactory.create();
    SummaryGeneratingListener listener = new SummaryGeneratingListener();
    launcher.registerTestExecutionListeners(listener);

    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
            .selectors(selectClass(clazz))
            .build();
    launcher.execute(request);
    //生成测试报告:
    List<String> resultList = new ArrayList<>();
    TestExecutionSummary summary = listener.getSummary();
    System.out.println("test results:");
    long totalTestsCount = summary.getTestsFoundCount();
    long failedTestsCount = summary.getTestsFailedCount();
    long succeededTestsCount = summary.getTestsSucceededCount();
    long spentTime = summary.getTimeFinished() - summary.getTimeStarted();
    if (failedTestsCount > 0) {
        for (TestExecutionSummary.Failure failure : summary.getFailures()) {
            StringBuilder sb = new StringBuilder();
            sb.append("method ")
                    .append(failure.getTestIdentifier().getDisplayName())
                    .append(": ")
                    .append(failure.getException());
            resultList.add(sb.toString());
        }
    }
    return resultList;
}

我将该程序打包为Jar包并在Ubuntu服务器上测试,运行正常:测试结果显示完整的统计信息,包含测试总数、成功数等,且被测试类中的HI!正常输出。

之后我将该脚本复制到Spring Boot应用的接口方法中,代码如下:

@RestController
public class TestRunnerController {

    @GetMapping("/run")
    public void runTest() throws Exception {
        //创建类加载器以加载CalculatorTest(JUnit5测试类)
        ClassLoader cl = new URLClassLoader(new URL[]{new File("/home/admin/test_folder").toURI().toURL()});
        //从test_folder中加载已编译的CalculatorTest类以启动JUnit5测试
        Class cls = cl.loadClass("CalculatorTest");
        //启动JUnit测试并打印测试结果
        System.out.println(runTest(cls));
    }

    public static List<String> runTest(Class clazz) {
        Launcher launcher = LauncherFactory.create();
        SummaryGeneratingListener listener = new SummaryGeneratingListener();
        launcher.registerTestExecutionListeners(listener);

        LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                .selectors(selectClass(clazz))
                .build();
        launcher.execute(request);
        List<String> resultList = new ArrayList<>();
        TestExecutionSummary summary = listener.getSummary();
        System.out.println("test results:");
        long totalTestsCount = summary.getTestsFoundCount();
        long failedTestsCount = summary.getTestsFailedCount();
        long succeededTestsCount = summary.getTestsSucceededCount();
        long spentTime = summary.getTimeFinished() - summary.getTimeStarted();
        if (failedTestsCount > 0) {
            for (TestExecutionSummary.Failure failure : summary.getFailures()) {
                StringBuilder sb = new StringBuilder();
                sb.append("method ")
                        .append(failure.getTestIdentifier().getDisplayName())
                        .append(": ")
                        .append(failure.getException());
                resultList.add(sb.toString());
            }
        }
        return resultList;
    }

}

我将Spring Boot项目打包为Jar包并运行,调用该接口后,脚本启动但未执行测试:仅输出test results:,测试总数、成功数、失败数均为0,返回空报告,甚至未输出被测试类中的HI!。

我推测问题源于Spring Boot项目中JUnit依赖的打包异常。以下是Spring Boot项目的pom配置:

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <version>1.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-commons</artifactId>
        <version>1.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-engine</artifactId>
        <version>1.8.2</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <mainClass>app.Application</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

以下是被测试的类:

public class Calculator {
    public int sum(int a, int b){
        System.out.println("HI!");
        return a+15+b;
    }
}

内容的提问来源于stack exchange,提问作者Alexander Tukanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:24:47