断言抛出多个异常

谁能告诉我如何使用断言抛出有几个例外?


对于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));

    }

}

和我的测试方法:


 @Test

void checkViolation(){

    comptabiliteManager = spy(ComptabiliteManagerImpl.class);

    when(vViolations.isEmpty()).thenReturn(false);


    assertThrows(  ConstraintViolationException.class, () ->comptabiliteManager.checkViolation(vViolations), "a string should be provided!");

}

我想匹配方法并完全抛出 ConstraintViolationException 和 FunctionalException


有什么想法吗?


慕桂英546537
浏览 160回答 2
2回答

白猪掌柜的

将引发一个异常,其类型为 。这是一个.FunctionalExceptioncauseFunctionalExceptionConstraintViolationException假设是&nbsp;JUnit 5 方法,它将返回引发的异常。因此,您可以简单地获取其原因并对此原因添加其他检查。assertThrows

慕村225694

我假设 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)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .hasCauseInstanceOf(ConstraintViolationException.class);您必须从 AssertJ 的 Assertions 类导入方法:import static org.assertj.core.api.Assertions.catchThrowable;import static org.assertj.core.api.Assertions.assertThat;我鼓励您查看此API,因为它具有许多流畅的方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java