Java 如何在代码覆盖率中包含Catch块:JaCoCo和Junit
我对朱尼特和杰科科是个新手。我正在尝试为catch块添加测试用例。但是我的JaCoCo代码覆盖率仍然要求我在代码覆盖率中覆盖catch块。 下面是我的方法和测试用例Java 如何在代码覆盖率中包含Catch块:JaCoCo和Junit,java,unit-testing,junit,jacoco,Java,Unit Testing,Junit,Jacoco,我对朱尼特和杰科科是个新手。我正在尝试为catch块添加测试用例。但是我的JaCoCo代码覆盖率仍然要求我在代码覆盖率中覆盖catch块。 下面是我的方法和测试用例 public Student addStudent(Student Stu) throws CustomException { try { // My Business Logic return Student; } catch (Exception e) { thro
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您的
警告RuntimeException
测试没有多大意义,因为目前整个studentService#addStudent
方法都被模拟了。所以()->studentService.addStudent(student)
调用不会在studentService
中执行real方法
如果你想测试studentService
,千万不要嘲笑它。您需要模拟mybusinesslogic
部分来抛出异常
举个例子:
public Student addStudent(Student stu)抛出自定义异常{
试一试{
Student savedStudent=myBusinessLogic.addStudent(stu);
留学生;
}捕获(例外e){
抛出新的CustomException(“添加学生时异常”,e);
}
}
@鬼鬼祟祟
@试验
公共无效例外(){
when(myBusinessLogic.addStudent(student)).thenthow(RuntimeException.class);
assertThrows(CustomException.class,()->studentService.addStudent(student));
}
您的警告RuntimeException
测试没有多大意义,因为当前整个studentService#addStudent
方法都被模拟了。所以()->studentService.addStudent(student)
调用不会在studentService
中执行real方法
如果你想测试studentService
,千万不要嘲笑它。您需要模拟mybusinesslogic
部分来抛出异常
举个例子:
public Student addStudent(Student stu)抛出自定义异常{
试一试{
Student savedStudent=myBusinessLogic.addStudent(stu);
留学生;
}捕获(例外e){
抛出新的CustomException(“添加学生时异常”,e);
}
}
@鬼鬼祟祟
@试验
公共无效例外(){
when(myBusinessLogic.addStudent(student)).thenthow(RuntimeException.class);
assertThrows(CustomException.class,()->studentService.addStudent(student));
}
感谢@Petr Aleksandrov的快速响应,如果我没有嘲笑StudentService,我就不能使用Mockito的when()。而且我也无法使业务逻辑失败,因为它再次调用了外部功能。如果你想测试StudentService,你不能模仿它。要测试catch块,需要在“业务逻辑”中的某个地方抛出异常。感谢@Petr Aleksandrov的快速响应,如果我没有模拟StudentService,我就无法使用Mockito的when()。而且我也无法使业务逻辑失败,因为它再次调用了外部功能。如果你想测试StudentService,你不能模仿它。为了测试catch块,需要在“业务逻辑”中的某个地方抛出异常。