亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

斷言拋出多個異常

斷言拋出多個異常

慕桂英546537 2022-08-17 15:53:02
誰能告訴我如何使用斷言拋出有幾個例外?對于ex,這里有一個類: protected void checkViolation(Set<ConstraintViolation<EcritureComptable>> vViolations) throws FunctionalException {    if (!vViolations.isEmpty()) {        throw new FunctionalException("L'écriture comptable ne respecte pas les règles de gestion.",                                      new ConstraintViolationException(                                          "L'écriture comptable ne respecte pas les contraintes de validation",                                          vViolations));    }}和我的測試方法: @Testvoid checkViolation(){    comptabiliteManager = spy(ComptabiliteManagerImpl.class);    when(vViolations.isEmpty()).thenReturn(false);    assertThrows(  ConstraintViolationException.class, () ->comptabiliteManager.checkViolation(vViolations), "a string should be provided!");}我想匹配方法并完全拋出 ConstraintViolationException 和 FunctionalException有什么想法嗎?
查看完整描述

2 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

將引發一個異常,其類型為 。這是一個.FunctionalExceptioncauseFunctionalExceptionConstraintViolationException

假設是 JUnit 5 方法,它將返回引發的異常。因此,您可以簡單地獲取其原因并對此原因添加其他檢查。assertThrows


查看完整回答
反對 回復 2022-08-17
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

我假設 ConstraintViolationException 將是 FunctionalException 的根本原因。在這種情況下,要檢查是否引發了異常,您可以執行如下操作:


Executable executable = () -> comptabiliteManager.checkViolation(vViolations);


Exception exception = assertThrows(FunctionalException.class, executable);


assertTrue(exception.getCause() instanceof ConstraintViolationException);

另一個可能更干凈的解決方案是使用AssertJ及其API。


Throwable throwable = catchThrowable(() -> comptabiliteManager.checkViolation(vViolations));


assertThat(throwable).isInstanceOf(FunctionalException.class)

            .hasCauseInstanceOf(ConstraintViolationException.class);

您必須從 AssertJ 的 Assertions 類導入方法:


import static org.assertj.core.api.Assertions.catchThrowable;

import static org.assertj.core.api.Assertions.assertThat;

我鼓勵您查看此API,因為它具有許多流暢的方法。


查看完整回答
反對 回復 2022-08-17
  • 2 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號