我有一个场景,我从方法调用中收到一个列表,我想断言该列表包含正确的元素。一种方法是在每个元素中查找一些细节以查看要与哪个预期元素进行比较 - 例如。一个名字。然而,元素还包含一个随机生成的 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 类的两个对象。如何比较两个列表中的所有狗?
奖励问题:如何在不知道顺序的情况下比较列表,或者我是否只需要断言预期的狗包含在列表中。
最佳答案
试试 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
关于java - 测试忽略某些字段的列表内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47560225/