【问题标题】:Testing content of list ignoring some of the fields忽略某些字段的列表测试内容
【发布时间】:2017-11-29 19:20:50
【问题描述】:

我有一个场景,我从方法调用中收到一个列表,我想断言该列表包含正确的元素。一种方法是在每个元素中查找一些细节,以查看要与哪个预期元素进行比较 - 例如。一个名字。但是,这些元素还包含一个随机生成的 UUID,我不关心比较。
然后我想一个测试工具可能会来救我。以下面的简化示例为例。

我有一个班狗:

public class Dog {
    private String name;
    private Integer age;
}

它们包含在一个列表中:

List<Dog> dogs = ... many dogs

现在我想测试该列表是否包含预期的狗,但由于某种原因我不知道某些字段 - 让我们说age。 我已经尝试使用 assertj 和 hamcrest,但我找不到正确的解决方案,既比较两个列表,同时也忽略一些字段。

到目前为止,这就是我所拥有的(使用 hamcrest):

List<Dog> actualDogs = codeUndertest.findDogs(new Owner("Basti"));
List<Dog> expectedDogs = createExpectedListOfDogsWithoutTheAge();

Matcher.assertThat(actualDogs.get(0), Matcher.is(com.shazam.shazamcrest.matcher.Matchers
    .sameBeanAs(expectedDogs.(0))
    .ignoring("age")
))

这可行,但它只比较 Dog 类的两个对象。如何比较两个列表中的所有狗?
额外的问题:我如何在不知道顺序的情况下比较列表,或者我只需要断言预期的狗包含在列表中。

【问题讨论】:

标签: java unit-testing hamcrest assertj


【解决方案1】:

试试 AssertJ 的usingElementComparatorIgnoringFields

Employee bill = new Employee("Bill", 60, "Micro$oft");
Employee appleBill = new Employee("Billie", 60, "Apple");
List<Employee> employees = newArrayList(bill, appleBill);

Employees[] expectedEmployees = { new Employee("Bill", 60, "Google"), 
                                  new Employee("Billie", 60, "Facebook") };
// this assertion succeeds as we don't compare the company field.     
assertThat(employees).usingElementComparatorIgnoringFields("company")
                     .contains(expectedEmployees);

编辑: 可以使用新的递归比较 API,它可以更好地控制正在比较的内容:https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-fields

【讨论】:

  • 如果我的 expectedDogs 是一个数组,我可以将其作为参数传递给 contains()。
【解决方案2】:

就我而言,我尝试比较不同类别的列表。 @Joel Costigliola 提示我使用 usingElementComparatorIgnoringFields,所以我写了这段代码:

List<ClassOne> input = new ArrayList<>();
input.add(...);
...
List<ClassTwo> result = new ArrayList<>();
...
assertThat(result).usingElementComparatorIgnoringFields("field1", "field2").isEqualTo(input);

【讨论】:

  • 虽然这可能会回答问题,但最好包括一些关于如何回答我帮助解决问题的描述。
猜你喜欢
  • 2017-04-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
相关资源
最近更新 更多