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

Java新手IntelliJ运行测试类报org/hamcrest/SelfDescribing类缺失错误求助

错误产生原因

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing 错误的根因是单元测试运行时类路径缺失Hamcrest依赖:JUnit 4.12及更高版本将原本内置的Hamcrest断言组件拆分出来作为独立依赖,测试执行过程中调用断言逻辑需要加载Hamcrest的SelfDescribing类时找不到对应类文件,就会抛出该错误。

修复方案

1. Maven项目

在pom.xml的dependencies节点中添加以下依赖即可,二选一即可:

  • 直接使用自带Hamcrest整合包的JUnit依赖:
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
  • 单独补充Hamcrest核心依赖:
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-core</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>

依赖添加完成后,点击IDEA右侧Maven面板的刷新按钮同步依赖,再重新运行测试类。

2. Gradle项目

在build.gradle的dependencies代码块中添加以下配置:

dependencies {
    testImplementation 'junit:junit:4.13.2'
    testImplementation 'org.hamcrest:hamcrest-core:2.2'
}

配置完成后刷新Gradle依赖,重新运行测试即可。

3. 无构建工具的原生IDEA项目

  • 下载对应版本的junit.jar和hamcrest-core.jar包
  • 打开IDEA顶部菜单栏 File > Project Structure > Modules > Dependencies
  • 点击面板右侧的+号,选择JARs or directories,选中下载的两个jar包导入
  • 将导入的两个依赖的作用域设置为Test,点击Apply保存配置后重新运行测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:54:07