【问题标题】:AssertJ usingRecursiveComparison fails when a class field is a collection当类字段是集合时,AssertJ usingRecursiveComparison 失败
【发布时间】:2020-10-22 05:51:30
【问题描述】:
class Person {
private List<Phone> phones;
}
class Phone {
private String number;
}
assertThat(result).usingRecursiveComparison()
.ignoringCollectionOrder()
.isEqualTo(expectedPerson);
expectedPerson 的电话号码和电话号码相同,但由于列表引用不一样,测试失败。如果我没记错的话,usingRecursiveComparison 只会比较价值。那么为什么这里会失败呢?
【问题讨论】:
标签:
java
unit-testing
junit5
assertj
【解决方案1】:
很遗憾,无法重现您的问题。
我想,可能是一些版本冲突或其他环境问题。例如,以下 sn-p 按预期工作:
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);
}
}
注意事项:
以下是来自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>