關於 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, 記錄結束,沒什么含金量,只是個工具而已,有需要的朋友拿去學習。