3

I want to use assertEquals() on the two lists list1 and list2.

The problem is, that I don't want to compare the lists like assertEquals(list1, list2). The elements are objects that can return their ids with a function getId(), and I want to check if the lists are equal in terms of the ids (ordered!).

How can I do that? Is functional programming a good idea?

Yanick Nedderhoff
  • 1,174
  • 3
  • 18
  • 35

5 Answers5

3

If you create the expected list with the ids of the objects in order, example

List<MyObject> expected = new ArrayList<>();
expected.add(myObject1); //with id = 1
expected.add(myObject2); //with id = 2
expected.add(myObject3); //with id = 3

assertEquals(expected, actual);

, then if the actual list has objects in different order of ids, it would fail.

Rahul Sharma
  • 892
  • 1
  • 6
  • 16
2

You could transform the lists to lists of ids and then compare them:

return list1.stream().map(MyClass::getId).collect(Collectors.toList())
    .equals(list2.stream().map(MyClass::getId).collect(Collectors.toList()));

This question is very similar to this question, so you can take more ideas from there. In my answer you can see that in one of the options I proposed is creating a reusable utility method for lists comparison:

<T, U> boolean equal(List<T> list1, List<T> list2, Function<T, U> mapper) {
    List<U> first = list1.stream().map(mapper).collect(Collectors.toList());
    List<U> second = list2.stream().map(mapper).collect(Collectors.toList());
    return first.equals(second);
}

Then all you need to write is:

return equal(list1, list2, MyClass::getId);
Community
  • 1
  • 1
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
2

You can use AssertJ fluent assertions library. Your comparison may looks like

// "id" need to be either a property or a public field
assertThat(list1).extracting("id").contains(list2);
Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41
  • This would incorrectly assert as true if list1 contains all of the same elements as list2, with some additional ones. If you made that same call one more time but flipping list1/list2 I think that would work as expected (although there are probably better ways to do this). – Mark Madej Nov 05 '20 at 21:24
0

I see this question as a duplicate of this . If you want to compare the objects only with id , simpler way is to override the equals method , as frameworks use it to assert if two objects are equal.

Community
  • 1
  • 1
Raghavan
  • 883
  • 1
  • 8
  • 19
  • In the future, please flag the question as a duplicate, rather than posting an answer saying it's a duplicate. – Rob Jun 30 '17 at 02:24
0

I didn't do it directly but instead first compared list size, then compared each element.

jwehrle
  • 4,414
  • 1
  • 17
  • 13