0

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);
}

enter image description here

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

1 Answers1

2

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));
    }
Petr Aleksandrov
  • 1,434
  • 9
  • 24
  • Thanks @Petr Aleksandrov for the quick response, If I didn't mock the StudentService I can't to use the when() of Mockito. And also I'm unable to make the business logic as failed because its calling an external functionality. – Manisha Murali Feb 12 '21 at 11:49
  • 1
    Again. If you want to test StudentService you must NOT mock it. To test that catch block the exception needs to be thrown somewhere in your 'business logic'. – Petr Aleksandrov Feb 12 '21 at 12:08