我对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,:11
发布于 2021-02-12 11:27:53
您的cautionRunTimeException测试没有多大意义,因为目前整个studentService#addStudent方法都是模拟的。因此,()-> studentService.addStudent(student)调用不会在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));
}https://stackoverflow.com/questions/66169846
复制相似问题