问题

如何在aJUnittest案例中对列表进行断言?不仅列表的大小,而且列表的内容。


#1 热门回答(114 赞)

我意识到这是几年前被问到的,可能这个功能不是那时候的。但是现在,这很容易做到:

@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.htmlhttp://junit.org/junit4/javadoc/latest/org/hamcrest/core/Is.html


#2 热门回答(18 赞)

这是一个传统的答案,适用于JUnit 4.3及更低版本。现代版本的JUnit在assertThat方法中包含内置的可读失败消息。如果可能的话,更喜欢这个问题的其他答案。

List<E> a = resultFromTest();
List<E> expected = Arrays.asList(new E(), new E(), ...);
assertTrue("Expected 'a' and 'expected' to be equal."+
            "\n  'a'        = "+a+
            "\n  'expected' = "+expected, 
            expected.equals(a));

正如@Paul在对这个答案的评论中提到的那样,两个List是相同的:

当且仅当指定的对象也是列表时,两个列表具有相同的大小,并且两个列表中的所有对应的元素对相等。 (如果(e1 == null?e2 == null:e1.equals(e2)),则两个元素e1和e2相等。)换句话说,如果两个列表包含相同顺序的相同元素,则它们被定义为相等。此定义确保equals方法在List接口的不同实现中正常工作。

请参阅List接口的JavaDocs。


#3 热门回答(16 赞)

不要转换为字符串并进行比较。这对于性能不利。在junit中,在Corematchers内部,有一个匹配器=> hasItems

List<Integer> yourList = Arrays.asList(1,2,3,4)    
assertThat(yourList, CoreMatchers.hasItems(1,2,3,4,5));

这是我知道检查列表中元素的更好方法。


原文链接