Search code examples
javajunithamcrest

JUnit Assert, Matchers and nested objects


I have the following collection:

Set<DecisionGroup> parentDecisionGroups

first of all in my test I need to check that this collection contains two objects with a given ids:

assertThat(parentDecisionGroups, hasItem(hasProperty("id", equalTo(decisionGroup1.getId()))));
assertThat(parentDecisionGroups, hasItem(hasProperty("id", equalTo(decisionGroup2.getId()))));

so far so good...

Right now I need to check that parentDecisionGroups.get(0).getOwnerDecision() (where parentDecisionGroup.id == decisionGroup1.getId()) is equals to decision1 and parentDecisionGroups.get(1).getOwnerDecision() (where parentDecisionGroup.id == decisionGroup2.getId()) is equals to decision2

how to do this with org.hamcrest.* and org.junit.Assert.* ?


Solution

  • You can use a CombinableMatcher to both(matcher1).and(matcher2) the matchers.

    So you'll get something like:

    assertThat(parentDecisionGroups, hasItem(
                   both(hasProperty("id", equalTo(decisionGroup1.getId()))).
                   and(hasProperty("ownerDecision", equalTo("decision1"))));