当类字段是集合时,AssertJ usingRecursiveComparison失败

问题描述

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

assertthat(result).usingRecursiveComparison()
        .ignoringCollectionorder()
        .isEqualTo(expectedPerson);

expectedPerson的电话号码和电话号码相同,但是测试失败,因为列表引用不同。如果我没记错的话,usingRecursiveComparison只会比较价值。那么为什么它失败了?

解决方法

很遗憾,无法重现您的问题。

我想,可能是某些版本冲突或其他环境问题。例如,以下代码片段按预期工作:

(?=\\)

enter image description here 注释: 以下是(?<=\\)[^\\\n]*Test[^\\\n]*(?=\\) 的相关依赖项:

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