断言等于 Junit 中的 2 个列表 [英] Assert equals between 2 Lists in Junit

查看:32
本文介绍了断言等于 Junit 中的 2 个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I make an equality assertion between lists in a JUnit test case? Equality should be between the content of the list.

例如:

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<写一个新答案/a>.

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

I realise this answer is written a couple years after the question, probably this feature wasn't around then. But now, it's easy to just do this:

@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,只需添加这些导入:

If you have a recent version of Junit installed with hamcrest, just add these imports:

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/最新/org/hamcrest/core/Is.html

这篇关于断言等于 Junit 中的 2 个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆