首页 > 解决方案 > 如何在代码覆盖中包含 Catch 块:JaCoCo 和 Junit

问题描述

我对 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,Java 版本:11

标签: javaunit-testingjunitjacoco

解决方案


您的cautionRunTimeException测试没有多大意义,因为目前整个studentService#addStudent方法都是模拟的。所以()-> studentService.addStudent(student)call 不会在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));
    }

推荐阅读