work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

jacoco多模块生成java单元测试报告实践

Posted on 2022-06-19 22:58  work hard work smart  阅读(629)  评论(0编辑  收藏  举报

1、根目录的pom.xml 文件

<plugin>
	<groupId>org.jacoco</groupId>
	<artifactId>jacoco-maven-plugin</artifactId>
	<version>0.8.7</version>
	<executions>
		<execution>
			<id>prepare-agent</id>
			<goals>
			   <goal>prepare-agent</goal>
			</goals>
		</execution>
	</executions>
</plugin>

  

模块关系

----parent

|---- test-module 单元测试模块

| ---- business-module1 业务模块1

| ---- business-module2 业务模块2

test-module 依赖 business-module1 和  business-module2

<!--把依赖的模块解压出来放到classes目录下,原依赖的模块都是jar包方式存在,mvn test时会找不到-->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <id>unpack</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>unpack</goal>
            </goals>
            <configuration>
                <artifactItems>
                    <!--把每个依赖的模块,都配置进来-->
                    <artifactItem>
                        <groupId>com.lishiots.cloud.datacenter</groupId>
                        <artifactId>datacenter-service</artifactId>
                        <version>1.0.1</version>
                        <type>jar</type>
                        <includes>**/*.class</includes>
                        <overWrite>false</overWrite>
                        <outputDirectory>${project.build.directory}/classes</outputDirectory>
                    </artifactItem>
                </artifactItems>
            </configuration>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <!--  junit 5 版本至少为2.22.2,且需要增加其他依赖 -->
    <version>2.7.1</version>
    <configuration>
        <runOrder>random</runOrder>
        <testFailureIgnore>true</testFailureIgnore>
    </configuration>
</plugin>
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.7</version>
    <executions>
        <!--整合所有子模块报告-->
        <execution>
            <id>report-aggregate</id>
            <phase>test</phase>
            <goals>
                <goal>report-aggregate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

  

所有的单元测试代码再test-module的src/test/java 下

test-module的pom.xml

 

依次执行如下命令

先编译

mvn clean -U -Dmaven.test.skip=true package

保证test-module的target/classes中存在依赖的模块代码
如果启动需要依赖yml文件,需要先替换target/classes/bootstart.yml中的占位符

再执行测试

mvn test

  

参考:https://www.jianshu.com/p/4c2af38bc85f

https://blog.csdn.net/skh2015java/article/details/121775806