温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring 异常单元测试的解决

发布时间:2020-10-06 18:34:40 来源:脚本之家 阅读:136 作者:张喜硕 栏目:编程语言

白盒测试,要求对代码中的每行代码至少覆盖一次。

@ApiModelProperty("学科类别")
@ManyToOne
// 设置学科类别字段不能为空
@JoinColumn(nullable = false)
@JsonView({NoneJsonView.class,
    MeasurementUnitCategoryJsonView.getAllByDisciplineId.class})
private Discipline discipline;

以之前对学科设置不为空为例,我们需要测试两种情况,为空时的异常和不为空时保存正常。

@Test
public void saveTest() {
  logger.debug("新建计量单位类别");
  MeasurementUnitCategory measurementUnitCategory = new MeasurementUnitCategory();

  logger.debug("测试保存");
  measurementUnitCategoryService.save(measurementUnitCategory);
}

这里我们调用了save方法,但是IDE并没有提示我们需要捕获异常,但是并不代表这个save方法不抛出异常,可以抛出非检查的RuntimeException或其派生的异常。

为了测试这个异常,我们首先运行这行代码,看看出现什么异常。

Spring 异常单元测试的解决

org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: org.h3.jdbc.JdbcSQLException: NULL not allowed for column "DISCIPLINE_ID"; SQL statement:
insert into measurement_unit_category (id, discipline_id, is_asc) values (null, ?, ?) [23502-194]

我们看到有三个异常,先是插入这条记录时的JdbcSQLException,然后该异常引起了ConstraintViolationException,新异常又引起了DataIntegrityViolationException

这个Caused by其实是异常的一种封装,比如说底层,可能会抛出异常,但是我们一般都是在比较高的层面去处理异常。

就拿这个来举例子,DataIntegrityViolationException数据违反异常,很多种可能都会产生这种异常,所以这种异常的处理方法都是相同或类似的。

当底层抛出了一个JdbcSQLException,然后调用它的方法就catch了这个异常,并用该异常构建了一个新的异常ConstraintViolationException(限制违反异常),然后再向上层抛出,再到上层捕获,构建新异常DataIntegrityViolationException并抛给了我们,我们没有处理,然后控制台就报错了。

这样一直封装向上抛的好处就是我可以用一个异常来处理一类相似的情况,然后在处理这个异常的时候可以追根溯源,一直精确到是由什么引起的。如果没有这个封装的话,那我们需要直接去catch底层的异常才能精确地定位到错误。

好了,我们这里需要捕获的异常就是应用抛给我们的DataIntegrityViolationException异常。

@Test
public void saveTest() {
  logger.debug("基础测试数据准备");
  MeasurementUnitCategory measurementUnitCategory = new MeasurementUnitCategory();
  Boolean catchException = false;

  logger.debug("测试保存,期待抛出异常");
  try {
    measurementUnitCategoryService.save(measurementUnitCategory);
  } catch (DataIntegrityViolationException e) {
    catchException = true;
  }

  logger.debug("断言捕获异常为真");
  assertThat(catchException).isTrue();
}

运行测试,通过。

Spring 异常单元测试的解决

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI