java - 在 Junit 中断言等于 2 个列表之间

标签 java unit-testing collections junit

如何在 JUnit 测试用例中的列表之间进行相等断言?列表内容之间应该相等。

例如:

List<String> numbers = Arrays.asList("one", "two", "three");
List<String> numbers2 = Arrays.asList("one", "two", "three");
List<String> numbers3 = Arrays.asList("one", "two", "four"); 

// numbers should be equal to numbers2
//numbers should not be equal to numbers3

最佳答案

对于junit4!这个问题值得为 junit5 写一个新的答案。 .

我意识到这个答案是在提出问题几年后写的,可能当时还没有这个功能。但是现在,这样做很容易:

@Test
public void test_array_pass()
{
  List<String> actual = Arrays.asList("fee", "fi", "foe");
  List<String> expected = Arrays.asList("fee", "fi", "foe");

  assertThat(actual, is(expected));
  assertThat(actual, is(not(expected)));
}

如果您使用 hamcrest 安装了最新版本的 Junit,只需添加以下导入:

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

http://junit.org/junit4/javadoc/latest/org/junit/Assert.html#assertThat(T, org.hamcrest.Matcher)

http://junit.org/junit4/javadoc/latest/org/hamcrest/CoreMatchers.html

http://junit.org/junit4/javadoc/latest/org/hamcrest/core/Is.html

关于java - 在 Junit 中断言等于 2 个列表之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3236880/

相关文章:

python - 我应该到处注释类型吗?

collections - 在 Cypher 中获取集合的第 n 个元素

c# - 如何构建这个 LINQ 表达式?

java - 泛型错误 : not applicable for the arguments

java - 需要一个基于 Java 的 HTML 美化器来清理 Velocity 生成的 HTML

Linux 上 Path 变量中的 Java

c# - 在单元测试中模拟 Automapper 是一种好习惯吗?

java - Azure Java 使用自己的 VHD 创建 Linux VM

java - 如何在 JUnit 测试中重复捕获循环中的参数?

c# - 删除单个集合中的重复项 C#