2017-02-18 75 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以供進一步閱讀)