简体   繁体   中英

AssertJ usingRecursiveComparison fails when a class field is a collection

class Person {
  private List<Phone> phones;
}
class Phone {
  private String number;
}

assertThat(result).usingRecursiveComparison()
        .ignoringCollectionOrder()
        .isEqualTo(expectedPerson);

The expectedPerson has the same number of phones and phone numbers, but the test fails because the list reference is not the same. If I recall correctly, usingRecursiveComparison would only compare value. So why here it fails?

Unfortunatelly, was not able to reproduce your problem.

I suppose, it might be some version conflicts or other environment issues. For example, following snippet is working as expected:

class Person {
    private final List<Phone> phones;

    Person(List<Phone> phones) {
        this.phones = phones;
    }
}

class Phone {
    private final String number;

    Phone(String number) {
        this.number = number;
    }
}

class PersonTest {
    @Test
    void samePerson() {

        Person expected = new Person(List.of(
                new Phone("2"),
                new Phone("3"),
                new Phone("1")));

        Person actual = new Person(List.of(
                new Phone("1"),
                new Phone("2"),
                new Phone("3")));

        assertThat(actual).usingRecursiveComparison()
                .ignoringCollectionOrder()
                .isEqualTo(expected);
    }
}

在此处输入图片说明 Notes: Here are relevant dependencies from pom.xml :

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.4.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <version>5.4.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>3.17.2</version>
      <scope>test</scope>
    </dependency>

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