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

JUnit 4.11中使用assertThat断言遇删除线及匹配器方法未定义错误的解决方案咨询

解决JUnit 4.11中assertThat过时及匹配器找不到的问题

嘿,我来帮你搞定这个JUnit断言的问题!你遇到的两个现象其实是相关的:

  1. assertThat显示删除线(过时):JUnit 4.11里org.junit.Assert类中的assertThat方法确实是过时的——它只是Hamcrest断言功能的一个包装,JUnit官方早就推荐直接使用Hamcrest原生的断言方式了。
  2. empty()、is()等匹配器报错:这些方法根本不属于JunitAssertions类(也不是JUnit自带的),它们是Hamcrest库提供的匹配器方法,你没导入正确的包自然找不到。

下面是具体的解决步骤:

第一步:确保项目引入Hamcrest依赖

JUnit 4.11虽然依赖Hamcrest,但默认可能只引入了核心包,而empty()这类更丰富的匹配器在hamcrest-library包里。根据你的构建工具添加依赖:

如果用Maven(pom.xml)

<dependencies>
    <!-- 保留原有的JUnit依赖,加上Hamcrest的两个包 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
</dependencies>

如果用Gradle(build.gradle)

dependencies {
    testImplementation 'junit:junit:4.11'
    testImplementation 'org.hamcrest:hamcrest-core:1.3'
    testImplementation 'org.hamcrest:hamcrest-library:1.3'
}

第二步:修改导入语句

把原来导入JUnit断言的语句替换成Hamcrest的正确导入:

  • 移除(或替换)import static org.junit.Assert.*;,换成Hamcrest的断言类和匹配器:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

你可以保留其他JUnit的断言导入(比如assertArrayEquals、assertTrue),这不影响。

第三步:修正测试代码

现在你的测试代码就可以正常运行了,修正后的示例如下:

package BasicsOfJava.BasicsOfJava;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
import static org.testng.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

public class JunitAssertions {
    @Test
    public void assertionsInJava() {
        List<String> emptyList = new ArrayList<>();
        assertThat(emptyList, empty()); // 不再过时,也不会报错
        // 还可以轻松使用其他Hamcrest匹配器
        assertThat("hello", is("hello"));
        assertThat(42, equalTo(42));
        assertThat(List.of(1,2,3), hasItem(2));
    }
}

简单总结下:JUnit 4.11的assertThat是弃用的过渡方法,真正的匹配器功能在Hamcrest库中,只要导入正确的包并引入依赖,就能正常使用所有匹配器啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:37:30