Issue
I want to verify that an expected exception meets certain criteria. Take this as a starting point:
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);
}
}
How do I assert, for example, that the thrown exception has n > 1
and message
contains only lowercase letters? I was thinking of using thrown.expect(Matcher)
but can't figure out how to get a Hamcrest matcher to check arbitrary fields of an object.
Solution
You can use TypeSafeMatcher
where you can provide your MyException
class, and then an IntPredicate
to check the n
value against a condition:
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");
}
}
Then you can expect like so:
thrown.expect(new MyExceptionMatcher(i -> i > 1));
Answered By - Lino
Answer Checked By - Mildred Charles (JavaFixing Admin)