2017-02-18 74 views
1

我有这样的代码相匹配:如何检查是否异常的原因的异常类型

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实现这一目标?

+0

您可以使用'e.getCause()instanceof CustomException'。 http://stackoverflow.com/questions/7526817/use-of-instance-of-in-java – aturkovic

+0

是的,但我想知道如果JUnit有一些办法做到这一点。因为如果我想检查多个异常,它很快就会变得丑陋。 'assertThat(e).isInstanceOf(IllegalArgumentException.class)'例如不再工作。我认为API已经改变。 –

回答

2

使用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!")); 
} 
+0

谢谢。它几乎完美。你可以把'ExecutionException.class'放在ex​​pect中,'CustomException.class'放在'isA'里面吗? 因为'CustomException'不被抛出。 'CustomException'是异常的原因。 我会立即接受它作为回答:) –

+0

如果你想捕捉异常而不是让你的代码失败,GhostCats的答案比使用ExpectedException更简单,如果你想让你的测试结束,我的例子可能会更好抛出异常。 – aturkovic

1

容易,你可以解决,使用 “内置” 的东西(规则是好的,但在这里不要求):

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

换句话说:只要拿起那个原因;然后断言需要声称的任何需求。 (我正在使用assertThat和is()匹配器;请参阅here以供进一步阅读)