经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
关于SpringBoot单元测试(cobertura生成覆盖率报告)
来源:jb51  时间:2021/11/22 18:46:09  对本文有异议

demo(SpringBoot 项目)

被测试类:

  1. import org.springframework.stereotype.Service;
  2. @Service
  3. public class TestService {
  4. public String sayHi() {
  5. return "hi";
  6. }
  7. public int divide(int a, int b) {
  8. return a / b;
  9. }
  10. }

测试代码:

  1. import static org.junit.Assert.*;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringRunner;
  7. @RunWith(SpringRunner.class)
  8. @SpringBootTest
  9. public class TestServiceTest {
  10. @Autowired
  11. TestService testService;
  12. @Test
  13. public void testSayHi() {
  14. TestService testService = new TestService();
  15. String result = testService.sayHi();
  16. assertEquals("hi", result);
  17. }
  18. @Test
  19. public void testDivide() {
  20. TestService testService = new TestService();
  21. int result = testService.divide(3, 6);
  22. assertTrue(result > -1);
  23. }
  24. }

pom.xml 配置文件

  1. ![cobertura](C:\Users\jiaflu\Desktop\cobertura.PNG)<?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.5.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.jiaflu</groupId>
  12. <artifactId>learn_springoot</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>learn_springoot</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <jackson.version>2.9.8</jackson.version>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-test</artifactId>
  28. <scope>test</scope>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-web</artifactId>
  33. </dependency>
  34. </dependencies>
  35. <build>
  36. <plugins>
  37. <plugin>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-maven-plugin</artifactId>
  40. </plugin>
  41. <plugin>
  42. <groupId>org.apache.maven.plugins</groupId>
  43. <artifactId>maven-compiler-plugin</artifactId>
  44. <configuration>
  45. <source>1.8</source>
  46. <target>1.8</target>
  47. </configuration>
  48. </plugin>
  49. <plugin>
  50. <groupId>org.apache.maven.plugins</groupId>
  51. <artifactId>maven-surefire-plugin</artifactId>
  52. <version>2.5</version>
  53. </plugin>
  54. <plugin>
  55. <groupId>org.codehaus.mojo</groupId>
  56. <artifactId>cobertura-maven-plugin</artifactId>
  57. <version>2.5.2</version>
  58. <configuration>
  59. <encoding>UTF-8</encoding>
  60. <formats>
  61. <format>html</format>
  62. <format>xml</format>
  63. </formats>
  64. </configuration>
  65. </plugin>
  66. </plugins>
  67. </build>
  68. </project>

运行mvn cobertura:cobertura 查看截图:

覆盖率测试报告生成(cobertura)

cobertura 原理

cobertura执行过程大致如下:

  • 使用instrument修改我们编译后的class文件,位于 target\generated-classes。
  • 执行测试,测试数据输出到xxx.ser中,位于 target\cobertura\cobertura.ser。
  • 使用report生成覆盖率报告。

1.instrument

instrument:cobertura使用instrument修改我们编译后的class文件,在代码里面加入cobertura的统计代码。并生成一个.ser文件(用于覆盖率数据的输出)。

使用 instrument 执行的过程中,CoberturaInstrumenter 会首先调用分析监听器分析给定的编译好的.class,获得touchPoint(可以认为对应于源代码中的待覆盖行)以及需要的其他信息。然后调用注入监听器将信息注入到新的.class中,保存到 \target\generated-classes 目录下。

示例:

  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by Fernflower decompiler)
  4. //
  5. package com.cisco.webex.cmse.soa.soaservice.service;
  6. import net.sourceforge.cobertura.coveragedata.HasBeenInstrumented;
  7. import net.sourceforge.cobertura.coveragedata.TouchCollector;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.context.annotation.PropertySource;
  12. import org.springframework.stereotype.Service;
  13. @PropertySource({"classpath:application.properties"})
  14. @Service
  15. public class PropertyService implements HasBeenInstrumented {
  16. private static final Logger logger;
  17. @Value("${cdp.instance.url}")
  18. private String cdpInstanUrl;
  19. @Value("${soa.instance.url}")
  20. private String soaInstanceUrl;
  21. @Value("${github.api.token}")
  22. public String gitApiToken;
  23. @Value("${github.instance.url}")
  24. private String githubInstance;
  25. @Value("${github.repo.template.owner}")
  26. private String tplRepoOwner;
  27. @Value("${github.repo.consul.owner}")
  28. private String consulRepoOwner;
  29. @Value("${slm.listen.queue.name}")
  30. private String slmListenQueue;
  31. public PropertyService() {
  32. boolean var1 = false;
  33. int __cobertura__branch__number__ = true;
  34. TouchCollector.touch("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 12);
  35. super();
  36. }
  37. public String getCdpInstanUrl() {
  38. boolean var1 = false;
  39. int __cobertura__branch__number__ = true;
  40. TouchCollector.touch("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 33);
  41. return this.cdpInstanUrl;
  42. }
  43. ...
  44. public void setSlmListenQueue(String ()V) {
  45. boolean var2 = false;
  46. int __cobertura__branch__number__ = true;
  47. TouchCollector.touch("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 85);
  48. this.slmListenQueue = slmListenQueue;
  49. TouchCollector.touch("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 86);
  50. }
  51. static {
  52. boolean var0 = false;
  53. boolean var1 = true;
  54. TouchCollector.touch("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 13);
  55. logger = LoggerFactory.getLogger(PropertyService.class);
  56. }
  57. }

2.执行测试

在执行测试用例时,引用 cobertura 修改过的.class,测试信息写入到cobertura.ser档案文件。

3.生成报告

从cobertura.ser获取覆盖率数据,然后结合src中提供的源代码,生成最终的覆盖率报告,放到了target\site\cobertura路径下。若配置了生成 html 格式的报告,可以通过 index.html 查看覆盖率测试报告。

SpringBoot pom.xml 配置

添加如下依赖:

  1. <plugin>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-maven-plugin</artifactId>
  4. </plugin>
  5. <plugin>
  6. <groupId>org.apache.maven.plugins</groupId>
  7. <artifactId>maven-compiler-plugin</artifactId>
  8. <configuration>
  9. <source>1.8</source>
  10. <target>1.8</target>
  11. </configuration>
  12. </plugin>
  13. <plugin>
  14. <groupId>org.apache.maven.plugins</groupId>
  15. <artifactId>maven-surefire-plugin</artifactId>
  16. <version>2.5</version>
  17. <configuration>
  18. <!-- 此参数用于解决一个坑,下面会说明 -->
  19. <argLine>-noverify</argLine>
  20. </configuration>
  21. </plugin>
  22. <plugin>
  23. <groupId>org.codehaus.mojo</groupId>
  24. <artifactId>cobertura-maven-plugin</artifactId>
  25. <version>2.5.2</version>
  26. <configuration>
  27. <formats>
  28. <format>xml</format>
  29. <format>html</format>
  30. </formats>
  31. </configuration>
  32. </plugin>

采坑:

在使用 mvn cobertura:cobertura 命令生成测试覆盖率报告时,出现了如下问题(截取部分,报错原因如下):

Reason:

Expected stackmap frame at this location.

Bytecode:

0x0000000: 2ab4 001b 2bb9 002e 0200 c600 2f2a b400

0x0000010: 1b2b b900 2e02 00c0 0030 b600 34c6 001c

解决方法:

本人使用的是 jdk1.8,添加 jvm 参数 -noverify,可以在 pom 文件中添加配置,配置见上述 pom.xml

网上查资料 jdk1.7 添加 jvm 参数 -XX:-UseSplitVerifier,(1.8没有 -XX:-UseSplitVerifier 这参数)

命令介绍

  • cobertura:check

根据最新的源码标记(生成的class文件)校验测试用例的覆盖率,如果没有达到要求,则执行失败.

  • cobertura:check-integration-test

这个命令和cobertura:check功能是一样的,区别是二者绑定的maven生命周期不一样.cobertura:check绑定了test, cobertura:check-integration-test绑定了verify.再说的明白些,maven生命周期中有一个是test跑得单元测试,还有一个是integration-test跑的集成测试.而verify前就是integration-test.即cobertura:check-integration-test比cobertura:check涵盖的测试用例更多.

  • cobertura:clean

这个好理解,就是清理掉目录/target/cobertura/中得文件.目前发现里面就一个文件cobertura.ser.

  • cobertura:cobertura

这个插件的关键命令.标记被编译的文件,运行单元测试,生成测试报告.

  • cobertura:cobertura-integration-test

和cobertura:cobertura做了一样的事情,区别是包含了集成测试用例.

  • cobertura:dump-datafile

在命令行输出覆盖率数据.数据依据是生成的class文件.这个命令我没搞懂他的意义何在.在后面一个有趣的实验我们会用这个命令来更好的理解cobertura-maven-plugin.

  • cobertura:help
  • cobertura:instrument

标记被编译的class文件.执行这个命令会在目录/target/generated-classes/cobertura下生成一套class文件.

maven-surefire-plugin 使用说明

Maven本身并不是一个单元测试框架,它只是在构建执行到特定生命周期阶段的时候,通过插件来执行JUnit或者TestNG的测试用例。这个插件就是maven-surefire-plugin,也可以称为测试运行器(Test Runner),它能兼容JUnit 3、JUnit 4以及TestNG。

在默认情况下,maven-surefire-plugin的test目标会自动执行测试源码路径(默认为src/test/java/)下所有符合一组命名模式的测试类。这组模式为:

  • */Test.java:任何子目录下所有命名以Test开关的Java类。
  • */Test.java:任何子目录下所有命名以Test结尾的Java类。
  • */TestCase.java:任何子目录下所有命名以TestCase结尾的Java类。

maven-surefire-plugin 插件应用:

1.跳过测试

跳过测试运行 mvn package -DskipTests

或者通过 pom 提供该属性:

  1. <plugin>
  2. <groupId>org.apache.maven.plugins</groupId>
  3. <artifactId>maven-surefire-plugin</artifactId>
  4. <version>2.5</version>
  5. <configuration>
  6. <skipTests>true</skipTests>
  7. </configuration>
  8. </plugin>

跳过测试代码的编译 mvn package -Dmaven.test.skip=true

或者通过 pom 提供该属性:

  1. <plugin>
  2. <groupId>org.apache.maven.plugin</groupId>
  3. <artifactId>maven-compiler-plugin</artifactId>
  4. <version>2.1</version>
  5. <configuration>
  6. <skip>true</skip>
  7. </configuration>
  8. </plugin>

2.动态指定要运行的测试用例

  1. mvn test -Dtest=RandomGeneratorTest

也可以使用通配符:

  1. mvn test -Dtest=Random*Test

或者也可以使用“,”号指定多个测试类:

  1. mvn test -Dtest=Random*Test,AccountCaptchaServiceTest

如果没有指定测试类,那么会报错并导致构建失败:

  1. mvn test -Dtest

这时候可以添加 -DfailIfNoTests=false 参数告诉 maven-surefire-plugin 即使没有任何测试也不要报错:

  1. mvn test -Dtest -DfailIfNoTests=false

3.包含与排除测试用例

  1. <plugin>
  2. <groupId>org.apache.maven.plugins</groupId>
  3. <artifactId>maven-surefire-plugin</artifactId>
  4. <version>2.5</version>
  5. <configuration>
  6. <includes>
  7. <include>**/*Tests.java</include>
  8. </includes>
  9. <excludes>
  10. <exclude>**/*ServiceTest.java</exclude>
  11. <exclude>**/TempDaoTest.java</exclude>
  12. </excludes>
  13. </configuration>
  14. </plugin>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号