1、编写类
package com.jacoco;
/**
* @author ybwei
* @Description
* @date 2021/8/31 13:27
**/
public class Add {
public int add(int a, int b) {
if (a == 20) {
return 20;
}
return a + b;
}
}
自行生成Test类快捷键,ctrl+shift+T或者在类中右键,选中Go To-->选择Test,弹窗中选中需要测试的方法,直接生成。
package com.jacoco;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Slf4j
public class AddTest {
private static Add add=new Add();
@BeforeEach
void setUp() {
log.info("setUp");
}
@AfterEach
void tearDown() {
log.info("tearDown");
}
@Test
void add() {
int sum = add.add(1, 2);
assertEquals(3, sum);
}
}
2、idea自带插件
注意:?测试的包名和开发的包名必须一致,否则会没有测试报告(报No coverage in ‘all classes in scope‘ in Intellij)。
执行Run 'AddTest' with Coverage
生成覆盖率
?
?3、jacoco插件
pom.xml
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.7</version>
<configuration>
<destFile>target/test-coverage/jacoco-unit.exec</destFile>
<dataFile>target/test-coverage/jacoco-unit.exec</dataFile>
</configuration>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
执行命令
mvn clean test -Dtest=com.jacoco.AddTest -Dmaven.test.failure.ignore=true verify
执行完成,在target/site/jacoco/index.html即可查看覆盖率图表。
?
|