hamcrest / JavaHamcrest

Java (and original) version of Hamcrest
http://hamcrest.org/
BSD 3-Clause "New" or "Revised" License
2.11k stars 379 forks source link

Allows to containsInAnyOrder with a Comparator #404

Open lhauspie opened 1 year ago

lhauspie commented 1 year ago

Sometimes, when we develop according to DDD principles, for aggregates and entities, we implement the equals method to compare instances based only on the identifier, not on all fields.

However, in tests, we'd like to ensure that a collection contains items based on all (or some) fields in addition to the identifier.

With this proposal, we'll be able to do just that with this type of code:

    assertThat(peoples,
        containsInAnyOrder(
            Comparator.<People, String>comparing(p -> p.getIdentifier())
                .thenComparing(p -> p.getFirstName())
                .thenComparing(p -> p.getLastName())
                .compare(o1, o2),
            new People(1, "John", "Doe"), new People(2, "Jane", "Doe")
        )
    );

If you agree with this proposal, I could extend this functionality to the IsIterableContainingInOrder and IsIterableContainingInRelativeOrder matchers.