Jordi
Jordi

Reputation: 23247

Hamcrest: Compare two custom class object collections

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?

Upvotes: 0

Views: 676

Answers (1)

Frank Neblung
Frank Neblung

Reputation: 3175

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

Upvotes: 1

Related Questions