Spring boot測試篇
代碼覆蓋率統計-jacoco
例子
pom.xml
<?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>
<groupId>com.ydfind</groupId>
<artifactId>spring-boot-test</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<properties>
<!-- 文件拷貝時編碼 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 同一套代碼多次打包時,後續打包進行資源覆蓋 -->
<maven.resources.overwrite>true</maven.resources.overwrite>
<!-- <!– 編譯時的編碼 –>-->
<!-- <maven.compiler.encoding>UTF-8</maven.compiler.encoding>-->
</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>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.3</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals><goal>prepare-agent</goal></goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals><goal>report</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
測試類
package com.ydfind.controller;
import com.ydfind.MainApp;
import com.ydfind.service.impl.MyServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = MainApp.class)
@RunWith(SpringRunner.class)
public class MyControllerTest {
@Autowired
private MyController myController;
@Autowired
private MyServiceImpl myService;
@Test
public void testName(){
System.out.println(myController.getName());
}
@Test
public void testService(){
myService.getServiceName();
}
}
結果一
結果二
com.ydfind.controller.MyControllerTest雖然會調用到service包裏代碼,但不會更新service的信息,但com.ydfind.MyControllerTest卻會。