概要:
我们在开发过程中通常都会编写单元测试用例,而jacoco插件可以在我们打包项目前设置生成单元测试覆盖报告,然后我们可以在浏览器中查看单元测试覆盖率。
1、使用H2内存数据库
首先要注意的是我们单元测试通常不要连接到数据库中,比如测试一个插入数据的接口,如果连接数据库会导致每次打包导致数据插入到数据库中,破坏数据。
引入h2需要jar包:
1 2 3 4 5 6 | <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> |
并且设置多个properties文件区分单测,研发,测试,生产环境。在单测文件中配置缓存数据库
1 2 3 4 | #单元测试配置 spring.datasource.driver-class-name=org.h2.Driver #内存模式 spring.datasource.url=jdbc:h2:mem:test |

2、配置jacoco插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <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.7.5.201505241946</version> <executions> <execution> <id>default-prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>default-report</id> <phase>prepare-package</phase> <goals> <goal>report</goal> </goals> </execution> <execution> <id>default-check</id> <phase>prepare-package</phase> <goals> <goal>check</goal> </goals> <configuration> <rules> <rule> <element>CLASS</element> <includes> <include>com.springboot.web.example.controller.*.*</include> <include>com.springboot.web.example.service.*.*</include> </includes> <limits> <limit> <counter>LINE</counter> <value>COVEREDRATIO</value> <minimum>0.00</minimum> </limit> </limits> </rule> </rules> </configuration> </execution> </executions> </plugin> </plugins> </build> |
3、控制台输入mvn clean package


4、拷贝报告文件路径,浏览器打开

红色表示未覆盖,绿色表示覆盖。通常覆盖率要求达到80%左右,具体根据项目情况。