【问题标题】:How to check if exception's cause matches a type of exception如何检查异常的原因是否与异常类型匹配
【发布时间】:2017-02-18 14:23:58
【问题描述】:

我有这个代码:

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 被抛出时,它是由另一个类中的另一个异常抛出的。我想检查导致 ExecutionException 的原始异常是否与我创建的一些自定义异常匹配。如何使用 JUnit 实现这一目标?

【问题讨论】:

  • 您可以使用e.getCause() instanceof CustomExceptionstackoverflow.com/questions/7526817/use-of-instance-of-in-java
  • 是的,但我想知道 JUnit 是否有办法做到这一点。因为如果我想检查多个异常,它很快就会变得丑陋。 assertThat(e).isInstanceOf(IllegalArgumentException.class) 例如不再起作用。我认为 API 发生了变化。

标签: java unit-testing junit4 completable-future


【解决方案1】:

像这样使用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!"));
}

【讨论】:

  • 谢谢。它几乎是完美的。你能把ExecutionException.class放在expect里面,把CustomException.class放在isA里面吗?因为CustomException 没有被抛出。 CustomException 是异常的原因。我会立即接受它作为答案:)
  • 如果您想捕获异常而不是让代码失败,GhostCats 的答案比使用 ExpectedException 更简单,如果您希望通过抛出异常结束测试,我的示例可能会更好。跨度>
【解决方案2】:

很简单,您可以使用“内置”的东西来解决这个问题(规则很好,但这里不需要):

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

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

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 2017-05-01
    相关资源
    最近更新 更多