我对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版本;6月5日,Java版本:11
您的< code > cautionRunTimeException 测试没有多大意义,因为目前整个< code > student service # addStudent 方法都被嘲笑。所以<代码>()-
如果你想测试< code>studentService,就不要嘲笑它。您更需要模拟< code >我的业务逻辑部分来抛出异常。
只是一个例子:
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));
}