Hamcrest - Matchers.hasProperty:如何检查对象列表是否包含具有具体值的对象
Hamcrest - Matchers.hasProperty: how to check if a List of objects contains an object with a concrete value
我在使用 Hamcrest 时遇到以下问题:
我有一份员工名单
List<Employee> employees = hamcrest.getEmployees();
其中:
public class Employee {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
和:
public List<Employee> getEmployees() {
Employee e1 = new Employee("Adam", 39, 18000);
Employee e2 = new Employee("Jola", 26, 8000);
Employee e3 = new Employee("Kamil", 64, 7700);
Employee e4 = new Employee("Mateusz", 27, 37000);
Employee e5 = new Employee("Joanna", 31, 12700);
Employee e6 = null;
return Arrays.asList(e1, e2, e3, e4, e5, e6);
}
我想检查我的列表中是否有名称为 Mateusz 的对象。
我已经尝试过这样的方式,但是出了点问题:
@Test
public void testListOfObjectsContains() {
List<Employee> employees = hamcrest.getEmployees();
assertThat(employees, Matchers.anyOf(Matchers.containsInAnyOrder(Matchers.hasProperty("name", is("Mateusz")), Matchers.hasProperty("age", is(27)))));
}
如何使用 Hamcrest 进行检查?
我花了 2 个多小时在互联网上找到解决方案,但不幸的是没有成功。
非常感谢您!
你需要匹配器hasItem
assertThat(
x,
hasItem(allOf(
Matchers.<Employee>hasProperty("name", is("Mateusz")),
Matchers.<Employee>hasProperty("age", is(27))
))
);
您也可以使用 hasItems
、contains
或 containsInAnyOrder
:
assertThat(
x,
hasItems( // or contains or containsInAnyOrder
Matchers.<Employee>hasProperty("name", is("Mateusz")),
Matchers.<Employee>hasProperty("age", is(27))
)
);
我在使用 Hamcrest 时遇到以下问题: 我有一份员工名单
List<Employee> employees = hamcrest.getEmployees();
其中:
public class Employee {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
和:
public List<Employee> getEmployees() {
Employee e1 = new Employee("Adam", 39, 18000);
Employee e2 = new Employee("Jola", 26, 8000);
Employee e3 = new Employee("Kamil", 64, 7700);
Employee e4 = new Employee("Mateusz", 27, 37000);
Employee e5 = new Employee("Joanna", 31, 12700);
Employee e6 = null;
return Arrays.asList(e1, e2, e3, e4, e5, e6);
}
我想检查我的列表中是否有名称为 Mateusz 的对象。 我已经尝试过这样的方式,但是出了点问题:
@Test
public void testListOfObjectsContains() {
List<Employee> employees = hamcrest.getEmployees();
assertThat(employees, Matchers.anyOf(Matchers.containsInAnyOrder(Matchers.hasProperty("name", is("Mateusz")), Matchers.hasProperty("age", is(27)))));
}
如何使用 Hamcrest 进行检查? 我花了 2 个多小时在互联网上找到解决方案,但不幸的是没有成功。
非常感谢您!
你需要匹配器hasItem
assertThat(
x,
hasItem(allOf(
Matchers.<Employee>hasProperty("name", is("Mateusz")),
Matchers.<Employee>hasProperty("age", is(27))
))
);
您也可以使用 hasItems
、contains
或 containsInAnyOrder
:
assertThat(
x,
hasItems( // or contains or containsInAnyOrder
Matchers.<Employee>hasProperty("name", is("Mateusz")),
Matchers.<Employee>hasProperty("age", is(27))
)
);