有没有办法构建一个组合的 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 结束,其中包含这些抛出的异常的集合:
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);
}
}
}
我想你可能正在寻找有属性 http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/beans/HasProperty.html or 有属性和值 http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/beans/HasPropertyWithValue.html
请参阅此处的示例:https://theholyjava.wordpress.com/2011/10/15/hasproperty-the-hidden-gem-of-hamcrest-and-assertthat/ https://theholyjava.wordpress.com/2011/10/15/hasproperty-the-hidden-gem-of-hamcrest-and-assertthat/
我以前处理过的另一个例子;在这里我们检查是否有Quote
method getModels()
返回一个集合PhoneModel
并且集合中的其中一项具有属性makeId
等于 LG_ID 且modelId
等于 NEXUS_4_ID。
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 http://docstore.mik.ua/orelly/java-ent/jnut/ch06_02.htm%20JavaBean惯例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)