IDEA中使用Jacoco统计单元测试的代码覆盖率

一:使用IDEA自带的代码覆盖率工具

1.查看配置(因为都是默认的,所以不用修改)

点击Edit Configurations
在这里插入图片描述
点击上方的设置图标用以修改整个Junit的配置,或者也可以点击具体的单元测试文件来修改该文件的配置
在这里插入图片描述
默认方式是IntelliJ IDEA
在这里插入图片描述
2.测试

选择想要测试的单元测试文件或者文件夹,右键Run with Coverage
在这里插入图片描述
成功后会出现统计信息
在这里插入图片描述
3.重要!!!

单元测试的结构目录必须与源码的工程目录相同,例如:
在这里插入图片描述
否则,可能会出不来统计信息
在这里插入图片描述

二:使用IDEA集成Jacoco(IDEA版本可能会有不同)

1.pom文件增加

        <dependency>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.2</version>
        </dependency>
        
        <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.2</version>
                <configuration>
                    <destFile>target/coverage-reports/jacoco-unit.exec</destFile>
                    <dataFile>target/coverage-reports/jacoco-unit.exec</dataFile>
                </configuration>
                <executions>
                    <execution>
                        <id>jacoco-initialize</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <!--这个report:对代码进行检测,然后生成index.html在 target/site/index.html中可以查看检测的详细结果-->
                    <execution>
                        <id>jacoco-site</id>
                        <phase>package</phase>
                        <!--<phase>test</phase>写上test的时候会自动出现site文件夹,而不需执行下面的jacoco:report步骤,推荐-->
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

刷新maven,会发现多了一个插件
在这里插入图片描述
2.运行测试用例

在插件中选择test或者是命令行运行mvn test
在这里插入图片描述
成功后target文件夹中会出现以下文件夹
在这里插入图片描述
此时.exec文件无法打开,需要使用jacoco插件打开。点击右侧jacoco插件
在这里插入图片描述
target文件夹中会多出一个site文件夹
在这里插入图片描述
点击里面的index.html文件,用浏览器打开即可看到测试报告
在这里插入图片描述
3.一个遇到的坑
工程目录最好不要有中文,如果有中文生成的.exec文件夹会包含乱码,然后生成到其他文件夹中(C/D盘根目录),此时jacoco插件在target文件夹中就找不到.exec文件,导致测试结果一直出不来

发布了16 篇原创文章 · 获赞 5 · 访问量 6634

猜你喜欢

转载自blog.csdn.net/xwj1992930/article/details/98212905