微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Assertj:如何按对象内容比较2个对象列表?

如何解决Assertj:如何按对象内容比较2个对象列表?

给出以下(快速和丢失)的代码

class Pair{
int x;
int y;
}

List l1 = Arrays.asList(new Match(1,2),new Match(1,3),new Match(2,3));
List l2 = Arrays.asList(new Match(1,3));

如何比较列表的内容? 到目前为止,我使用的所有方法都会检查对象本身是否相等,而不是对象值:

assertthat(l1).isEqualTo(l2);
assertthat(l1).containsAll(l2);
assertthat(l1).containsExactly(values);
assertthat(l1).containsExactlyElementsOf(iterable);

我必须为Match类实现equals()方法吗?

这可能是正确的方法吗?

for (int i = 0; i < l1.size(); i++){
    assertthat(l1.get(i)).usingRecursiveComparison().isEqualTol2.get(i));
}

请告知。 谢谢!

解决方法

我猜你应该重写equals()和hashCode()

,

尝试使用usingRecursiveFieldByFieldElementComparator(recursiveConfiguration),它可以与所有可迭代的断言进行递归比较。

例如:

public class Person {
  String name;
  boolean hasPhd;
}

public class Doctor {
  String name;
  boolean hasPhd;
}

Doctor drSheldon = new Doctor("Sheldon Cooper",true);
Doctor drLeonard = new Doctor("Leonard Hofstadter",true);
Doctor drRaj = new Doctor("Raj Koothrappali",true);

Person sheldon = new Person("Sheldon Cooper",false);
Person leonard = new Person("Leonard Hofstadter",false);
Person raj = new Person("Raj Koothrappali",false);
Person howard = new Person("Howard Wolowitz",false);

List<Doctor> doctors = list(drSheldon,drLeonard,drRaj);
List<Person> people = list(sheldon,leonard,raj);

RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                 .withIgnoredFields("hasPhd")
                                                                                 .build();

// assertion succeeds as both lists contains equivalent items in order.
assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
                   .contains(sheldon);

有关详细说明,请参见https://assertj.github.io/doc/#assertj-core-recursive-comparison-for-iterable

,

@vincentdep是正确的。如果您使用的是Java 14或更高版本,则可以使用record类:

public record Pair(int x,int y){};

List l1 = Arrays.asList(new Pair(1,2),new Pair(1,3),new Pair(2,3));
List l2 = Arrays.asList(new Pair(1,3));

assertThat(l1).isEqualTo(l2);
assertThat(l1).containsAll(l2);
,

是的,所以在进一步研究之后,我建议:

for (int i = 0; i < l1.size(); i++){
    assertThat(l1.get(i)).usingRecursiveComparison().isEqualTol2.get(i));
}

您可以阅读详细信息:

https://assertj.github.io/doc/#assertj-core-recursive-comparison

谢谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。