Java 如何将Hamcrest匹配器应用于被测类的属性?

Java 如何将Hamcrest匹配器应用于被测类的属性?,java,junit,hamcrest,junit-rule,Java,Junit,Hamcrest,Junit Rule,有没有一种方法可以构建一个组合的Hamcrest matcher来测试一个对象和这个对象的属性伪代码: both( instanceof(MultipleFailureException.class) ).and( // pseudo code starts adapt( new Adapter<MultipleFailureException, Iterable<Throwable>() { public Iterable<Thr

有没有一种方法可以构建一个组合的Hamcrest matcher来测试一个对象和这个对象的属性伪代码:

both(
  instanceof(MultipleFailureException.class)
).and(
  // pseudo code starts
  adapt(
    new Adapter<MultipleFailureException, Iterable<Throwable>()
    {
      public Iterable<Throwable> getAdapter(MultipleFailureException item)
      {
        return item.getFailures();
      }
    }, 
    // pseudo code ends
    everyItem(instanceOf(IllegalArgumentException.class))
  )
)

我想你可能在找或者

有关示例,请参见此处:

我以前工作过的另一个例子;这里我们检查是否有一个
Quote
方法
getModels()
返回
PhoneModel
的集合,并且集合中的一个项具有一个属性
makeId
,该属性等于LG\u ID,而
modeid
则等于NEXUS\u 4\u ID

            assertThat(quote.getModels(),
                            hasItem(Matchers.<PhoneModel> hasProperty("makeId",
                                            equalTo(LG_ID))));
            assertThat(quote.getModels(),
                            hasItem(Matchers.<PhoneModel> hasProperty("modelId",
                                            equalTo(NEXUS_4_ID))));
    }
assertThat(quote.getModels(),
hasItem(Matchers.hasProperty(“makeId”),
equalTo(LG_ID));
断言(quote.getModels(),
hasItem(Matchers.hasProperty(“modelId”),
equalTo(NEXUS_4_ID));
}
要想让它发挥作用,hamcrest依赖于您采用约定

            assertThat(quote.getModels(),
                            hasItem(Matchers.<PhoneModel> hasProperty("makeId",
                                            equalTo(LG_ID))));
            assertThat(quote.getModels(),
                            hasItem(Matchers.<PhoneModel> hasProperty("modelId",
                                            equalTo(NEXUS_4_ID))));
    }