springboot2.1.3+jacoco检测代码覆盖率
关于 jacoco的介绍,不在本文中详细描述,简单点说,只是个代码覆盖率工具,想要了解具体的可以参考如下地址:
https://www.jianshu.com/p/639e51c76544
好了,闲话不多说,上代码,先看下pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.szl.demo</groupId> <artifactId>szldemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>szldemo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <jacoco.version>0.8.3</jacoco.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <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>${jacoco.version}</version> <executions> <execution> <id>default-prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>default-report</id> <phase>test</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
新建一个简单的service类,用于后面的测试,如下:
package com.szl.demo.szldemo.service; public class Calculator { public int add(int a, int b) { return a + b; } public int sub(int a, int b) { return a - b; } }
写个单元测试类,如下:
package com.szl.demo.szldemo.service; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class CalculatorTest { private Calculator instance = new Calculator(); @Test public void testAdd() { int a = 10; int b = 20; int expected = 30; Assert.assertEquals(expected, instance.add(a, b)); } @Test public void testSub() { int a = 10; int b = 20; int expected = -10; Assert.assertEquals(expected, instance.sub(a, b)); } }
让我们进入控制台输入命令,或使用eclipse工具也可以实现,如下图:
这样,我们就成功生成了jacoco report了,我们可以去target/site/目录下就可找到。
打开index.html,我们就可以查看想看的内容了。
OK, 记录结束,没什么含金量,只是个工具而已,有需要的朋友拿去学习。