首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在代码覆盖率中包含Catch块: JaCoCo和Junit

如何在代码覆盖率中包含Catch块: JaCoCo和Junit
EN

Stack Overflow用户
提问于 2021-02-12 10:08:30
回答 1查看 1.4K关注 0票数 0

我对Junit和JaCoCo非常陌生。我正在尝试为catch块添加测试用例。但是,我的JaCoCo代码覆盖率仍然要求我在代码覆盖率中覆盖catch块。以下是我的方法和测试案例。

代码语言:javascript
复制
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,:11

EN

回答 1

Stack Overflow用户

发布于 2021-02-12 11:27:53

您的cautionRunTimeException测试没有多大意义,因为目前整个studentService#addStudent方法都是模拟的。因此,()-> studentService.addStudent(student)调用不会在studentService中执行真正的方法。

如果您想测试studentService,就不能嘲笑它。您需要模拟My Business Logic部分来抛出异常。

举个例子:

代码语言:javascript
复制
    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));
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66169846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档