java - 如何在代码覆盖中包含 Catch 块:JaCoCo 和 Junit
问题描述
我对 Junit 和 JaCoCo 很陌生。我正在尝试为 catch 块添加测试用例。但是我的 JaCoCo 代码覆盖率仍然要求我覆盖代码覆盖率中的 catch 块。以下是我的方法和测试用例。
public Student addStudent(Student Stu) throws CustomException {
try {
// My Business Logic
return Student;
} catch (Exception e) {
throw new CustomException("Exception while Adding Student ", e);
}
}
@SneakyThrows
@Test
public void cautionRunTimeException(){
when(studentService.addStudent(student)).thenThrow(RuntimeException.class);
assertThrows(RuntimeException.class,()-> studentService.addStudent(student));
verify(studentService).addStudent(student);
}
请分享我catch块代码覆盖的正确方法。
注:JaCoCo 版本:0.8.5,Junit 版本;junit5,Java 版本:11
解决方案
您的cautionRunTimeException
测试没有多大意义,因为目前整个studentService#addStudent
方法都是模拟的。所以()-> studentService.addStudent(student)
call 不会在studentService
.
如果你想测试studentService
它一定不能被嘲笑。您宁愿需要模拟部分My Business Logic
部分以引发异常。
只是一个例子:
public Student addStudent(Student stu) throws CustomException {
try {
Student savedStudent = myBusinessLogic.addStudent(stu);
return student;
} catch (Exception e) {
throw new CustomException("Exception while Adding Student ", e);
}
}
@SneakyThrows
@Test
public void cautionCustomException(){
when(myBusinessLogic.addStudent(student)).thenThrow(RuntimeException.class);
assertThrows(CustomException.class, ()-> studentService.addStudent(student));
}
推荐阅读
- python - 无法在 Docker Continummio/anaconda3 上构建映像
- angular - 订阅后调用 next 时,如何获取订阅中 Observable 的最后发出值?
- python - 如何获取在 pyglet 中播放的当前源的名称?
- django - 将您自己的链接添加到 django 管理面板的标题
- flutter - 发布包时出错:pub 以退出代码 1 结束
- javascript - 使用 javascript 将数据导出到 csv 以获取产品表
- javascript - Firebase 文件上传工作了一段时间,但随后失败
- python - 没有为 selenium 定义名称驱动程序
- installation - 如何在不使用 npm 命令的情况下安装电子?
- python - impl.NotFoundError:发现 2 个根错误