为了账号安全,请及时绑定邮箱和手机立即绑定

断言抛出多个异常

断言抛出多个异常

慕桂英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 关注
  • 159 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号