Hamcrest - Matchers.hasProperty: how to check if a List of objects contains an object with a concrete value
Asked Answered
P

2

8

I have the following problem with Hamcrest: I have a List of Employee

List<Employee> employees = hamcrest.getEmployees();

where:

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;
    }

and:

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);
    }

I'd like to check if there is an object with name = Mateusz in my list. I've tried in such a way, but something get wrong:

@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)))));
}

How can I check this using Hamcrest? I've spent over 2 hours to find the solution in Internet but unfortunately without success.

Thank you very much in advance!

Patnode answered 4/5, 2018 at 20:55 Comment(0)
M
11

You need the matcher hasItem

assertThat(
  x,
  hasItem(allOf(
    Matchers.<Employee>hasProperty("name", is("Mateusz")),
    Matchers.<Employee>hasProperty("age", is(27))
  ))
);
Mauer answered 4/5, 2018 at 21:53 Comment(1)
I was about to write: just write a custom matcher, but obviously: using a built-in matcher is match better ;-)Bessiebessy
P
3

You can also use hasItems, contains or containsInAnyOrder :

assertThat(
  x,
  hasItems( // or contains or containsInAnyOrder 
    Matchers.<Employee>hasProperty("name", is("Mateusz")),
    Matchers.<Employee>hasProperty("age", is(27))
  )
);
Pseudocarp answered 18/3, 2019 at 17:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.