是否有一种方法来构建一个组合Hamcrest匹配器测试对象和这个对象的属性?-伪代码:
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))
)
)
背景:我有一个JUnit测试,它在一组动态对象上迭代。每个对象在处理时都会抛出异常。收集异常。测试将以MultipleFailureException结束,该MultipleFailureException包含以下抛出异常的集合:
protected final ExpectedException expectation = ExpectedException.none();
protected final ErrorCollector collector = new ErrorCollector();
@Rule
public RuleChain exceptionRules = RuleChain.outerRule(expectation).around(collector);
@Test
public void testIllegalEnumConstant()
{
expectation.expect(/* pseudo code from above */);
for (Object object : ILLEGAL_OBJECTS)
{
try
{
object.processWithThrow();
}
catch (Throwable T)
{
collector.addError(T);
}
}
}
我想你可能正在寻找hasProperty或hasPropertyWithValue
请看这里的例子:https://theholyjava.wordpress.com/2011/10/15/hasproperty-the-hidden-gem-of-hamcrest-and-assertthat/
另一个我以前工作过的例子;这里我们检查是否有一个Quote
方法,getModels()
返回PhoneModel
的集合,并且集合中的一个项目具有等于LG_ID的属性makeId
和等于NEXUS_4_ID的属性modelId
。
assertThat(quote.getModels(),
hasItem(Matchers.<PhoneModel> hasProperty("makeId",
equalTo(LG_ID))));
assertThat(quote.getModels(),
hasItem(Matchers.<PhoneModel> hasProperty("modelId",
equalTo(NEXUS_4_ID))));
}
要使其工作,hamcrest依赖于您采用JavaBean约定。