最近项目到了联调阶段,主管需要我通过Jacoco计算一下测试用例的覆盖率,并生成一份测试用例覆盖率报告。
1、引入依赖
<dependencies>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.0.3.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<propertyName>surefireArgLine</propertyName>
</configuration>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/jacoco.exec</dataFile>
<outputDirectory>${basedir}/target/site/jacoco</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<!--suppress UnresolvedMavenProperty -->
<argLine>${surefireArgLine}</argLine>
<skipTests>false</skipTests>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
上面的pom配置需要放到你需要生报告的pom.xml中,比如这里我配置到了ops-biz包下的pom.xml里面。
相关测试用例也必须放到ops-biz的test下面,这样才能在ops-biz包下生成对应的用例覆盖率报告
2、测试用例
/**
* @Description:ClueInfoServiceTest
* @Author:zhangzhixiang
*/
@RunWith(SpringRunner.class)
public class ClueInfoServiceTest {
@Mock
private ClueInfoDAO clueInfoDAO;
@InjectMocks
private ClueInfoService clueinfoservice = new ClueInfoServiceImpl();
@Before
public void init() {
when(clueInfoDao.isExist(any(ClueInfoDO.class))).thenReturn(1L);
}
@Test
public void isExist() {
//case01
ClueInfoBO clueInfoBO = new ClueInfoBO();
Boolean flag = clueInfoService.isExist(clueInfoBO);
Assert.assertEquals(true, flag);
//case02
when(clueInfoDao.isExist(any(ClueInfoDO.class))).thenReturn(null);
Boolean flag = clueInfoService.isExist(clueInfoBO);
Assert.assertEquals(false, flag);
//case03
when(clueInfoDao.isExist(any(ClueInfoDO.class))).thenReturn(-1L);
Boolean flag = clueInfoService.isExist(clueInfoBO);
Assert.assertEquals(false, flag);
}
}
3、运行maven命令
mvn clean verify -DfailIfNoTests=false
之后用例覆盖率报告就会在/ops-biz/target/site文件夹下面生成。