【问题标题】:Fix for the message "The method empty() is undefined for the type JunitAssertions"修复消息“JunitAssertions 类型的方法 empty() 未定义”
【发布时间】:2021-01-19 15:52:31
【问题描述】:

我正在使用 Junit 断言。我在使用 assertThat 时遇到问题。下面的代码显示“assertThat”已被删除。 此外,无论我使用什么匹配器,比如 empty,equalsTo 我都会收到错误消息,因为“JunitAssertions 类型的方法 empty() 是未定义的”。 我项目中使用的Junit版本是4.11。

我的问题是使用 assertThat 断言需要做什么?

从我的项目中复制的代码:

package BasicsOfJava.BasicsOfJava;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
import static org.testng.Assert.assertEquals;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class JunitAssertions {

    @Test
    public void assertionsInJava()
    {   
           List<String> emptyList = new ArrayList<>();
            **assertThat**(emptyList, empty());
            Note : In my editor, assertThat is struck.      
                  
    }

【问题讨论】:

    标签: junit junit4 junit5 hamcrest


    【解决方案1】:

    assertThatHamcrest 的断言方法。 JUnit 决定不再支持这些断言,因为 Hamcrest 提供了自己的assertThat(请参阅PR 1150)。对您来说,这意味着添加导入

    import static org.hamcrest.MatcherAssert.assertThat
    

    和删除

    import static org.junit.Assert.*
    

    如果你只使用 Hamcrest 断言。您还需要为 empty() 之类的匹配器进行静态导入。基本匹配器在类CoreMatchers

    import static org.hamcrest.Matchers.*;
    

    【讨论】:

    • 感谢您的解决方案。这消除了与 assertThat 相关的错误。然而,我面临着相关匹配器的问题。由于没有建议,我无法添加静态导入。悬停时,显示消息“JunitAssertions 类型的方法 empty() 未定义”。它还建议为 empty() 创建一个方法。
    • 下次请阅读Hamcrest tutorial。该示例已修复:您必须添加 import static org.hamcrest.Matchers.*; 我相应地修复了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多