heeh
heeh

Reputation: 67

Comparing ArrayList in a unit test

Hello I was trying to test assertEquals() with an ArrayList. This is a part of my test code:

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

It looks like exactly same to me, but the junit says

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

Could anyone point out what I have done wrong?

Upvotes: 2

Views: 3887

Answers (4)

Serhii Shevchyk
Serhii Shevchyk

Reputation: 39436

Compare arrays instead of lists:

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

Upvotes: 0

Keppil
Keppil

Reputation: 46209

Comparing with a String won't work, but you don't need to create an ArrayList specifically to make the comparison, any List will do. Therefore you can use the method Arrays.asList():

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

Upvotes: 1

assylias
assylias

Reputation: 328568

n is a List whereas "[a, b, c]" is a string - the latter is a (possible) representation of the former but they are definitely not equal.

Upvotes: 1

Jeff Storey
Jeff Storey

Reputation: 57162

You're comparing a list to a string

Try something like

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

Upvotes: 6

Related Questions