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

JUnit 5无法使用:‘cannot resolve symbol `Assertions`’问题求助

解决JUnit 5中cannot resolve symbol 'Assertions'错误的方法

首先明确:不需要将JUnit Jar放到系统路径,这既不规范也容易引发其他问题,正确的解决方式分以下两种场景:

一、使用构建工具(Maven/Gradle)的项目

Maven 配置

在项目的pom.xml中添加JUnit 5的核心依赖:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.9.2</version> <!-- 建议使用最新稳定版本 -->
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>

添加后,执行mvn clean compile刷新依赖,或者在IDE中右键项目选择「Reload All Maven Projects」。

Gradle 配置

Groovy DSL(build.gradle)

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.2'
}

test {
    useJUnitPlatform()
}

Kotlin DSL(build.gradle.kts)

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.2")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
}

tasks.test {
    useJUnitPlatform()
}

执行gradle build --refresh-dependencies刷新依赖,或在IDE中点击Gradle面板的「Refresh」按钮。

二、手动管理依赖的非构建工具项目

  1. 下载所需Jar包:前往JUnit官网下载junit-jupiter-api-xxx.jar、junit-jupiter-engine-xxx.jar以及依赖apiguardian-api-xxx.jar(xxx为对应版本号,如5.9.2)。
  2. 在IDE中添加依赖:
    • IntelliJ IDEA:右键项目 → 「Open Module Settings」 → 「Libraries」 → 点击「+」选择「Java」 → 选中下载的所有Jar包 → 确认添加到测试模块依赖。
    • Eclipse:右键项目 → 「Build Path」 → 「Add External Archives」 → 选中下载的Jar包 → 确认后Jar会被加入Test Libraries。
  3. 确保测试类位于测试源代码目录(如src/test/java),IDE会自动识别该目录并应用测试依赖。

三、额外排查要点

  • 检查导入语句:确保测试类中导入的是JUnit 5的Assertions,正确导入示例:
    import static org.junit.jupiter.api.Assertions.*;
    // 或
    import org.junit.jupiter.api.Assertions;
    
    不要误导入JUnit 4的org.junit.Assert。
  • 避免版本冲突:不要同时引入JUnit 4和JUnit 5的依赖,会导致符号解析混乱。
  • 清理IDE缓存:若依赖已正确配置但报错未消失,尝试清理缓存:
    • IntelliJ:「File」→「Invalidate Caches...」→ 选择「Invalidate and Restart」。
    • Eclipse:「Project」→「Clean」→ 选中项目后点击「Clean」。

内容的提问来源于stack exchange,提问作者Mr.Trollo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:48:30