Jacoco安装
前往 地址下载,如下所示:
然后解压到自定义的目录即可:
在lib目录下看到有几个jar文件,其中jacocoagent.jar是在作为agent时用到,jacocoant.jar是结合ant使用的,jacococli.jar是命令行时会用到。
新建Springboot项目
这里只是为了演示,只新建一个简单的spring-boot项目,就一个简单的获取数字的平方的接口:
使用agent启动服务
java -javaagent:./jacocoagent.jar=destfile=./target/coverage.exec -jar ./target/jacocodemo-0.0.1-SNAPSHOT.jar
然后根据实际的测试用例调用一下接口,这里的逻辑很简单,比如:接口参数一个是0,一个是4即可。如:http://localhost:8080/power/0和http://localhost:8080/power/4。
生成覆盖率报告
调用完接口后,即可把服务停了,此时会生成coverage.exec文件,可以执行命令来生成html形式的报告:java -jar jacococli.jar report coverage.exec --classfiles F:\code\Java\jacocodemo\target\classes --html ./target/。
另外,在启动agent的时候,可以指定启动参数以实现更多自定义的过滤:
可以参考文档了解更多。
这里只是提供一个简单集成示例,这个步骤后续应该集成到devops系统来实现自动化的测试与报告生成,不用人工这么低效的逐步执行。