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

查看:177
本文介绍了断言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

推荐答案

我意识到这是几年前提出的,可能那时还没有.但是现在,只需执行以下操作即可:

I realise this was asked a couple years ago, 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/Latest/org/hamcrest/core/Is.html

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

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