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

Maven无法运行JUnit5测试求助(已引入Surefire插件)

问题根源与解决方案

我一眼就看到问题所在了——你的测试方法没有添加@Test注解!

具体分析:

你虽然在测试类里导入了org.junit.jupiter.api.Test,但你的test()方法上并没有标注这个注解。JUnit 5(以及所有JUnit版本)都是通过这个注解来识别测试方法的,Maven Surefire插件会扫描带有@Test注解的方法来执行测试,没有这个注解的普通方法会被直接忽略。

至于你提到Eclipse可以执行测试,大概率是你手动运行了这个普通方法,而非通过Eclipse的JUnit测试 runner 执行——如果用JUnit runner运行,它同样会找不到符合要求的测试方法。

修复步骤:

只需要给test()方法加上@Test注解即可:

package app; 
import static org.junit.jupiter.api.Assertions.*; 
import org.junit.jupiter.api.Test; 
import java.net.URL; 
import javax.swing.JOptionPane; 

class AppTest { 
    @Test // 新增这个注解!
    void test() { 
        System.out.println( "*************" ); 
        URL resURL = getClass().getClassLoader().getResource( "ResFile.txt" ); 
        System.out.println( resURL ); 
        assertNotNull( resURL ); 
        if ( resURL != null ) { 
            System.out.println( resURL.getPath() ); 
        } 
    } 
}

额外优化建议:

你的JUnit依赖版本存在不一致(junit-jupiter-engine是5.3.1,junit-jupiter-api是5.3.2),虽然这不是当前问题的诱因,但建议统一版本号避免潜在兼容性问题,比如都改为5.3.2:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>

修改后重新运行mvn test,Surefire插件就能正常识别并执行你的测试方法了。

内容的提问来源于stack exchange,提问作者Jack Straub

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:52:41