[英]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!"));
}
很簡單,您可以使用“內置”的東西解決該問題(規則很不錯,但此處不是必需的):
catch (ExecutionException e) {
assertThat(e.getCause(), is(SomeException.class));
換句話說:獲取原因。 然后斷言需要斷言的所有內容。 (我正在使用assertThat和is()匹配器;有關更多信息,請參見此處 )
如果您只想檢查異常的類型,可以很容易地完成
假設我們期望 SQLIntegrityConstraintViolationException 是原因,那么當我們有異常 object 時,我們可以檢查其原因的 class 類型,例如:
Exception ex = Assertion.assertThrows(RuntimeExcpetion.class, () -> someMethodWhichWillThrowRuntimeException());
Assertions.assertEquals(SQLIntegrityConstraintViolationException.class, ex.getCause().getClass());
希望這可以幫助!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.