【问题标题】:How to include the Catch block in code coverage : JaCoCo and Junit如何在代码覆盖中包含 Catch 块:JaCoCo 和 Junit
【发布时间】:2021-02-12 10:08:30
【问题描述】:

我对 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

【问题讨论】:

    标签: java unit-testing junit jacoco


    【解决方案1】:

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

    【讨论】:

    • 感谢@Petr Aleksandrov 的快速响应,如果我没有模拟 StudentService,我将无法使用 Mockito 的 when()。而且我无法使业务逻辑失败,因为它调用了外部功能。
    • 再次。如果你想测试 StudentService,你不能模拟它。要测试该 catch 块,需要在“业务逻辑”中的某处抛出异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2012-06-11
    • 2017-07-05
    • 2014-11-09
    • 2017-04-19
    相关资源
    最近更新 更多