我想验证预期的异常是否满足某些条件。以此为起点:
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 匹配器检查对象的任意字段。
一个简洁明了的替代方法是使用 AssertJ 而不是 ExpectException 规则。
assertThatThrownBy(() -> {
throw new MyException("x", 10);
})
.matches(e -> e.getMessage().equals(e.getMessage().toLower()), "message is lowercase")
.matches(e -> ((CustomException) e).n > 10, "n > 10");
您可以使用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));
Hamcrest中还有FeatureMatcher
,非常适合为对象的嵌套"特征"创建匹配器。因此,在您的示例中,您可以通过以下方式使用FeatureMatcher
构建它(这是我在为嵌套字段创建匹配器时倾向于遵循的模式(:
public final class MyExceptionMatchers {
public static Matcher<MyException> withNthat(Matcher<Integer> nMatcher) {
return new FeatureMatcher<MyException, Integer>(nMatcher, "n", "n") {
@Override
protected Integer featureValueOf(MyException actual) {
return actual.n;
}
}
};
}
在您的测试中:
import static x.y.z.MyExceptionMatchers.withNthat;
import static org.hamcrest.Matchers.greaterThan;
...
thrown.expect(withNThat(greaterThan(1)));
使用这种布局,很容易为MyException
添加更多匹配器,并且感觉像是一种更"规范"的方法来构建可组合匹配器,允许您为测试用例构建所需的确切匹配器。