在单元测试中比较ArrayList

时间:2013-07-23 19:53:55

标签: java junit

您好我试图用ArrayList测试assertEquals()。 这是我的测试代码的一部分:

ArrayList<String> n = new ArrayList<String>();
n.add("a");
n.add("b");
n.add("c");
assertEquals(n, "[a, b, c]");

对我来说看起来完全一样,但junit说

junit.framework.AssertionFailedError: expected:<[a, b, c]> but was:<[a, b, c]>

有人能指出我做错了吗?

4 个答案:

答案 0 :(得分:6)

您正在将列表与字符串进行比较

尝试类似

的内容
List<String> expected = new ArrayList<String>();
expected.add("a");
expected.add("b");
expected.add("c");
assertEquals(expected,n);

答案 1 :(得分:1)

n是一个List,而"[a, b, c]"是一个字符串 - 后者是前者的(可能)表示,但它们绝对不相等。

答案 2 :(得分:1)

String相比无效,但您无需专门创建ArrayList进行比较,任何List都可以。因此,您可以使用方法Arrays.asList()

assertEquals(Arrays.asList("a", "b", "c"), n);

答案 3 :(得分:0)

比较数组而不是列表:

  List<String> expected = new ArrayList<String>();
  expected.add("1");
  expected.add("2");
  expected.add("3");
  Assert.assertArrayEquals(expected.toArray(), new String[]{"1", "2", "3"});