Search code examples
javajunithamcrest

Compare subfields in hamcrest


Is there a way to compare the value of a subfield with hamcrest?

class Obj{
    NestedObj nestedObj;
}

class NestedObj{
    String wantedProperty;
}

I have a List<Obj> objs, and I want to test that all Objs have a wantedProperty with value "wanted":

List<Obj> objs = new ArrayList<Obj>();

Obj obj = new Obj();
NestedObj nestedObj = new NestedObj();
nestedObj.setWantedProperty("wanted");
obj.setNestedObj(nestedObj);
objs.add(obj);

assertThat(objs, hasItems(Matchers.<Obj>hasProperty("nestedObj.wantedProperty", hasValue("wanted"))));

But nestedObj.wantedProperty do not works.

How can I get it work, if it is possible?


Solution

  • try something like this

    assertThat(objs, hasItems(Matchers.<Obj>hasProperty("nestedObj", Matchers.<NestedObj>hasProperty("wantedProperty",equalTo("wanted")))));