2

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?

4 Answers 4

6

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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);

Comments

0

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"});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.