0

I've two Collection<Audit> collections:

Collection<Audit> pendingAudits;
Collection<Audit> olderAudits;

So, I need to compare all pendingAudits elements are in olderAudits.

In order to compare them, it's necessary to compare that each audit.getId().equals(other.getId()).

Please, take in mind I'm not able to override Audit.equals or Audit.hashCode. It's a third-party class.

I guess I need to create a custom inline Matcher.

Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • 2
    Possible duplicate of [Hamcrest compare collections](https://stackoverflow.com/questions/21624592/hamcrest-compare-collections) – Tom Oct 23 '18 at 12:46
  • Please read the other question and yes, you obviously need to override `equals` and `hashCode` – Tom Oct 23 '18 at 12:48
  • Please, read post again. Related question is comparing plain strings! – Jordi Oct 23 '18 at 12:58
  • 1
    That's right and your edited ___important___ information into question after I've linked the question. Thank you for hiding crucial information. – Tom Oct 23 '18 at 13:08
  • I do agree with @Tom. Since you would like to know how to compare two collections, and not to use the Hamcrest the way you should... here: `return first.size() == second.size() && first.stream().noneMatch(f -> second.stream().anyMatch(s -> f.getId() != s.getId()));` – dbl Oct 23 '18 at 13:21

1 Answers1

1

In the case that you want to give assertj a try, you could benefit from its custom comparison strategy

@Test
void myTest() {
    Collection<Audit> pendingAudits = ...
    Collection<Audit> olderAudits = ...

    Comparator<Audit> byId = Comparator.comparing(Audit::getId);
    assertThat(olderAudits).usingElementComparator(byId).containsAll(pendingAudits);
}
Frank Neblung
  • 3,047
  • 17
  • 34