如何检查异常的原因是否与异常类型匹配

How to check if exception's cause matches a type of exception

我有这个代码:

CompletableFuture<SomeClass> future = someInstance.getSomething(-902);
try {
    future.get(15, TimeUnit.SECONDS);
    fail("Print some error");
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    // Here I want to check if e.getCause() matches some exception
} catch (TimeoutException e) {
    e.printStackTrace();
}

所以当一个ExecutionException被抛出时,它被另一个class中的另一个异常抛出。我想检查导致 ExecutionException 的原始异常是否与我创建的某些自定义异常匹配。我如何使用 JUnit 实现这一目标?

像这样使用ExpectedException

@Rule
public final ExpectedException expectedException = ExpectedException.none();

@Test
public void testExceptionCause() throws Exception {
    expectedException.expect(ExecutionException.class);
    expectedException.expectCause(isA(CustomException.class));

    throw new ExecutionException(new CustomException("My message!"));
}

很简单,你可以使用 "built-in" 东西解决这个问题(规则很好,但这里不需要):

catch (ExecutionException e) {
  assertThat(e.getCause(), is(SomeException.class));

换句话说:只获取那个原因;然后断言任何需要断言的东西。 (我正在使用 assertThat 和 is() 匹配器;请参阅 here 进一步阅读)