白盒测试,要求对代码中的每行代码至少覆盖一次。
|
1
2
3
4
5
6
7
|
@apimodelproperty("学科类别")
@manytoone
// 设置学科类别字段不能为空
@joincolumn(nullable = false)
@jsonview({nonejsonview.class,
measurementunitcategoryjsonview.getallbydisciplineid.class})
private discipline discipline;
|
以之前对学科设置不为空为例,我们需要测试两种情况,为空时的异常和不为空时保存正常。
|
1
2
3
4
5
6
7
8
|
@test
public void savetest() {
logger.debug("新建计量单位类别");
measurementunitcategory measurementunitcategory = new measurementunitcategory();
logger.debug("测试保存");
measurementunitcategoryservice.save(measurementunitcategory);
}
|
这里我们调用了save方法,但是ide并没有提示我们需要捕获异常,但是并不代表这个save方法不抛出异常,可以抛出非检查的runtimeexception或其派生的异常。
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.h2.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异常。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@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();
}
|
运行测试,通过。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:https://segmentfault.com/a/1190000015206760
相关文章
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-25 82
-
2025-06-04 98
-
2025-05-29 52
-
2025-05-25 82
-
2025-05-25 60



