6

I am writing JUnit Test case for my java project and using Coverage Tool to check the lines of code are covered. The problem is: I've two list of objects. I need to compare the results of object to be equal using assertTrue or any other possible assert statements. I am getting error like Assertion Error by using below assert statements. Is there any solution to compare two lists easily?

//actual    
List<ProjectData> actuals = ProjectManagerDao.getProjects("x", "y", "z");
// expected
List<ProjectData> expecteds = new ArrayList<>();
ProjectData p1 = new ProjectData();
p1.setId("a");
p1.setName("b");
expecteds.add(p1);

assertTrue(JsonProvider.getGson().toJson(actuals).equalsIgnoreCase(JsonProvider.getGson().toJson(expecteds)));
//or
assertTrue(actuals.equalIgnoreCase(expeteds);//Not working for list of objects but working for comparing two strings

This differs from Java Compare Two Lists in that I need to be able to assert equality in jUnit, not just compare the lists.

Community
  • 1
  • 1
SRIRAM RAMACHANDRAN
  • 297
  • 3
  • 8
  • 23

3 Answers3

6

Use Assert.assertArrayEquals(Object[] expecteds, Object[] actuals) method to compare two array for content equality:

Assert.assertArrayEquals(expected.toArray(), actuals.toArray());

equals method compares arrays for being the same reference so it's not suitable in test cases.

For your other question: Remember to use org.junit.Assert not junit.Assert which became obsolete.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
4

In short: there is exactly one assert that one needs when writing JUnit tests: assertThat

You just write code like

assertThat("optional message printed on fails", actualArrayListWhatever, is(expectedArrayListWhatever))

where is() is a hamcrest matcher.

This approach does work for all kinds of collections and stuff; and it does the natural "compare element by element" thing (and there are plenty of other hamcrest matcher that one can use for more specific testing; and it is also pretty easy to write your own matchers).

( seriously; I have not seen a single case where assertThat() would not work; or would result in less readable code )

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You can use

Assert.assertEquals(java.lang.Object expected, java.lang.Object actual);

example:

ArrayList<String> list1 = new ArrayList<>();
list1.add("hello");
ArrayList<String> list2 = new ArrayList<>();
list2.add("hello");
Assert.assertEquals(list1, list2);

source: Junit API

or if you want to use the arrays comparison method you can as below

ArrayList<String> list1;
ArrayList<String> list2;

Assert.assertArrayEquals(list1.toArray(), list2.toArray());

I would recommend you to use the assertEquals method.

PS: (the user defined objects stored inside the list should have the equals and hashcode methods overridden)

Praveen Kumar
  • 1,515
  • 1
  • 21
  • 39