Reputation: 49
I'm quite new to Junit and JaCoCo. I'm trying to add test case for the catch block. But my JaCoCo code coverage is still asking me to cover the catch block in code coverage. Following is my method and testcase.
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);
}
Please share me the correct way for the code coverage of catch block.
Note: JaCoCo version: 0.8.5, Junit version; junit5, Java version: 11
Upvotes: 0
Views: 3378
Reputation: 1524
Your cautionRunTimeException
test doesn't make much sense because currently the whole studentService#addStudent
method is mocked. So ()-> studentService.addStudent(student)
call doesn't execute real method in studentService
.
If you want to test studentService
it mustn't be mocked. You rather need to mock part of My Business Logic
section to throw the exception.
Just an example:
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));
}
Upvotes: 2