当 class 字段是一个集合时,AssertJ usingRecursiveComparison 失败
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);
expectedPerson
的phone个数和phone个数相同,但是测试失败,因为列表引用不一样。如果我没记错的话,usingRecursiveComparison
只会比较值。那么为什么它在这里失败了?
很遗憾,无法重现您的问题。
我想,可能是版本冲突或者其他环境问题。例如,以下代码段按预期工作:
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>
class Person {
private List<Phone> phones;
}
class Phone {
private String number;
}
assertThat(result).usingRecursiveComparison()
.ignoringCollectionOrder()
.isEqualTo(expectedPerson);
expectedPerson
的phone个数和phone个数相同,但是测试失败,因为列表引用不一样。如果我没记错的话,usingRecursiveComparison
只会比较值。那么为什么它在这里失败了?
很遗憾,无法重现您的问题。
我想,可能是版本冲突或者其他环境问题。例如,以下代码段按预期工作:
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>