【问题背景】
使用Junit框架编写单元测试用例大家都比较熟悉,最近项目需要开发一个操作系统隔离的命令执行CBB模块,我们在本地IDEA编写的单元测试用例只能在本地Windows环境运行,项目需要将Junit4的单元测试用例编译后放到不同的操作系统环境执行,验证CBB模块在不同操作系统环境下执行的有效性。
【解决思路和详细步骤】
一、通过Maven编译包含生产代码、三方依赖和单元测试用例的fat jar
1.1 IDEA下的Maven工程路径如下图:
1.2 pom文件中添加Junit依赖和test目录打包
dependency依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
test目录打包:
<!-- 在pom.xml中添加一个新的Maven Profile -->
<profiles>
<profile>
<id>package-tests</id>
<build>
<plugins>
<!-- 配置maven-compiler-plugin编译包括测试代码 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version> <!-- 请确保使用最新稳定版 -->
<configuration>
<testIncludes>
<testInclude>src/test/java/com/*</testInclude>
</testIncludes>
</configuration>
</plugin>
<!-- 使用maven-assembly-plugin自定义打包结构 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<descriptors>
<descriptor>src/main/resources/assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
assembly.xml 文件内容如下:
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>fat-tests</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<useProjectArtifact>true</useProjectArtifact>
<unpack>true</unpack>
<scope>test</scope>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<directory>${project.build.directory}/test-classes</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>**/*.class</include>
</includes>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>
1.3 Maven命令对生产代码、依赖包、测试代码打fat jar
mvn clean package -Ppackage-tests
二、将fat jar部署到不同的操作系统环境运行测试用例
java -cp common-building-block-fat-tests.jar org.junit.runner.JUnitCore com.winicssec.cbbapi.util.WntI18nUtilTests