简体   繁体   中英

How to assertThat a list of objects has a set of properties with certain values

Using the Hamcrest library, I need to assert that a list of objects with specific properties (java beans) matches a set of properties. For example, if we had a list of Person objects with firstName, lastName, and middleName properties I've tried the following:

assertThat(personObjectList, either(contains(
      hasProperty("firstName", is("Bob")),
      hasProperty("lastName", is("Smith")),
      hasProperty("middleName", is("R.")))
.or(contains(
      hasProperty("firstName", is("Alex")),
      hasProperty("lastName", is("Black")),
      hasProperty("middleName", is("T."))));

But in execution the properties of the objects are not obtained, I just get a comparison against the Object T, output like:

but: was Person@7bd7c4cf, was Person@5b9df3b3

Is there a way to accomplish what I'm trying to do here using Hamcrest? This works when doing a single contains, but when doing two contains with either() I receive the output above.

You can use anyOf method . For example:

List<Person> persins = Arrays.asList( new Person("Bob", "Smith", "R."));

assertThat(persons, contains(anyOf(
      sameProprtyValues(new Person("Bob", "Smith", "R.")),
      sameProprtyValues(new Person("Alex", "Black", "T.")) 
));

If you want to use several properties, you should try:

assertThat(persons, contains(
    either(
            both(hasProperty("firstName", is("Bob")))
            .and(hasProperty("lastName", is("Smith")))
            .and(hasProperty("middleName", is("R.")))
    ).or(
            both(hasProperty("firstName", is("Alex")))
            .and(hasProperty("lastName", is("Black")))
            .and(hasProperty("middleName", is("T.")))
    )
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM