Java 如何检查是否存在异常';s原因与异常类型匹配
我有以下代码:Java 如何检查是否存在异常';s原因与异常类型匹配,java,unit-testing,junit4,completable-future,Java,Unit Testing,Junit4,Completable Future,我有以下代码: CompletableFuture<SomeClass> future = someInstance.getSomething(-902); try { future.get(15, TimeUnit.SECONDS); fail("Print some error"); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e)
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();
}
CompletableFuture=someInstance.getSomething(-902);
试一试{
future.get(15,时间单位:秒);
失败(“打印一些错误”);
}捕捉(中断异常e){
e、 printStackTrace();
}捕获(执行例外){
//这里我想检查e.getCause()是否匹配一些异常
}捕获(超时异常e){
e、 printStackTrace();
}
因此,当抛出ExecutionException时,它是由另一个类中的另一个异常抛出的。我想检查导致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!"));
}
很简单,您可以使用“内置”的东西解决这个问题(规则很好,但这里不需要):
换言之:只要找到原因;然后断言需要断言的任何东西。(我正在使用assertThat和is()匹配器;有关详细信息,请参阅)您可以使用CustomException的
e.getCause()实例。是的,但我想知道JUnit是否有办法做到这一点。因为如果我想检查多个异常,它很快就会变得丑陋<例如,代码>断言(e).isInstanceOf(IllegalArgumentException.class)
不再起作用。我想API已经改变了。谢谢。这几乎是完美的。请将ExecutionException.class
放入expect和CustomException.class
中isA
?因为不会抛出CustomException
<代码>自定义异常是异常的原因。我将立即接受它作为答案:)如果您希望捕获异常而不是让代码失败,GhostCats答案比使用ExpectedException更简单,如果您希望通过抛出异常来结束测试,我的示例可能会更好。
catch (ExecutionException e) {
assertThat(e.getCause(), is(SomeException.class));