在 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

原文由 Kamal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
1 个回答

对于 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)));
}

如果你安装了最新版本的 Junit 和 hamcrest,只需添加这些导入:

 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

原文由 djeikyb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题