我的自定义对象如下所示:

@Accessors(chain = true)
@Getter
@Setter
@AllArgsConstructor
@ToString
public class SocialLink {

    private String platform;

    private String link;
}


我的测试代码如下:

SocialLink[] arr1 = new SocialLink[] {
        new SocialLink("Facebook", "Facebook Link"),
        new SocialLink("Google", "Google Link")
};
SocialLink[] arr2 = new SocialLink[] {
        new SocialLink("Google", "Google Link"),
        new SocialLink("Facebook", "Facebook Link")
};
assertThat(arr1).containsOnly(arr2);


故障日志:

java.lang.AssertionError:
Expecting:
  <[SocialLink(platform=Facebook, link=Facebook Link),
    SocialLink(platform=Google, link=Google Link)]>
to contain only:
  <[SocialLink(platform=Google, link=Google Link),
    SocialLink(platform=Facebook, link=Facebook Link)]>
elements not found:
  <[SocialLink(platform=Google, link=Google Link),
    SocialLink(platform=Facebook, link=Facebook Link)]>
and elements not expected:
  <[SocialLink(platform=Facebook, link=Facebook Link),
    SocialLink(platform=Google, link=Google Link)]>


containsOnly()方法可以很好地处理字符串数组,但是为什么不适用于自定义对象数组呢?

最佳答案

如果您不希望或无法覆盖等于,那么可以尝试将usingRecursiveComparisonignoringAllOverriddenEquals结合使用(默认情况下,递归比较在被覆盖时使用等于)或更细粒度的替代方法ignoringOverriddenEqualsForTypesignoringOverriddenEqualsForFieldsignoringOverriddenEqualsForFieldsMatchingRegexes

 assertThat(links1).usingRecursiveComparison()
                   .ignoringAllOverriddenEquals()
                   .ignoringCollectionOrder()
                   .isEqualTo(expectedLinks);


请注意,递归比较目前仅提供isEqualTo断言。

有关详细信息,请参见https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals

10-06 16:13