JUnit Assert, Matchers and nested objects

梦想的初衷 提交于 2019-12-13 02:50:03

问题


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:


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


来源:https://stackoverflow.com/questions/47133052/junit-assert-matchers-and-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!