JUnit Assert, Matchers and nested objects

2019-08-19 09:15发布

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.* ?

1条回答
Evening l夕情丶
2楼-- · 2019-08-19 09:48

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"))));
查看更多
登录 后发表回答