我想验证预期的例外是否符合某些条件。以此为起点:
class MyException extends RuntimeException {
int n;
public MyException(String message, int n) {
super(message);
this.n = n;
}
}
public class HowDoIDoThis {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void test1() {
thrown.expect(MyException.class);
throw new MyException("x", 10);
}
}
例如,如何断言抛出的异常具有
n > 1
并且message
仅包含小写字母?我当时在考虑使用thrown.expect(Matcher)
,但无法弄清楚如何使Hamcrest匹配器检查对象的任意字段。 最佳答案
您可以使用TypeSafeMatcher
来提供MyException
类,然后使用IntPredicate
来根据条件检查n
值:
public class MyExceptionMatcher extends TypeSafeMatcher<MyException> {
private final IntPredicate predicate;
public MyExceptionMatcher(IntPredicate predicate) {
this.predicate = predicate;
}
@Override
protected boolean matchesSafely(MyException item) {
return predicate.test(item.n);
}
@Override
public void describeTo(Description description) {
description.appendText("my exception which matches predicate");
}
}
然后,您可以期望像这样:
thrown.expect(new MyExceptionMatcher(i -> i > 1));