We use JUnit 3 at work and there is no ExpectedException
annotation. I wanted to add a utility to our code to wrap this:
try {
someCode();
@FunctionalInterface
public interface ThrowingConsumer {
void accept(T t) throws E;
}
public static Consumer errConsumerWrapper(ThrowingConsumer throwingConsumer,
Class exceptionClass,
Consumer exceptionConsumer) {
return i -> {
try {
throwingConsumer.accept(i);
} catch (Exception ex) {
try {
exceptionConsumer.accept(exceptionClass.cast(ex));
} catch (ClassCastException ccEx) {
throw new RuntimeException(ex);
}
}
};
}
Usage example
Stream.of("a").forEach(errConsumerWrapper(i -> Integer.parseInt(i), NumberFormatException.class, Throwable::printStackTrace));