如何让Maven Assembly插件将JUnit依赖打入可执行Fat Jar?
问题解决:maven-assembly-plugin打包时包含JUnit依赖
问题根源
你的JUnit依赖在pom.xml里设置了<scope>test</scope>,Maven中test作用域的依赖仅用于测试代码的编译和执行,默认不会被maven-assembly-plugin的jar-with-dependencies描述符打包进去——该描述符只包含compile和runtime作用域的依赖,这就是运行时找不到org.junit.Assert的原因。
另外需要注意:你的主类MyTest的main方法直接调用了JUnit的assertEquals,这个依赖已经是程序运行必需的,从设计上来说不应该再放在test作用域下。
解决方案
方案一(推荐):调整JUnit依赖的作用域
把JUnit依赖的<scope>test</scope>移除(Maven默认依赖作用域就是compile),这样maven-assembly-plugin会自动把它打包进fat jar:
修改后的pom.xml依赖部分:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 移除test scope,使用默认的compile作用域 --> </dependency> </dependencies>
方案二(仅特殊场景使用):强制插件包含test作用域依赖
如果坚持要保留test作用域,可以在maven-assembly-plugin的配置里添加dependencySets,明确指定包含test作用域的依赖:
修改后的插件配置:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.6</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>first.second.MyTest</mainClass> </manifest> </archive> <!-- 添加以下配置,强制包含test作用域的JUnit依赖 --> <dependencySets> <dependencySet> <scope>test</scope> <includes> <include>junit:junit</include> </includes> <outputDirectory>/</outputDirectory> <useProjectArtifact>false</useProjectArtifact> <unpack>true</unpack> </dependencySet> </dependencySets> </configuration> <executions> <execution> <id>assemble-all</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin>
验证步骤
- 执行Maven打包命令:
mvn clean package - 运行生成的fat jar:
java -cp mytestapp-0.0.1-SNAPSHOT-jar-with-dependencies.jar first.second.MyTest - 此时应该只会输出
MyTest main,不会再抛出NoClassDefFoundError异常。
内容的提问来源于stack exchange,提问作者parsecer
相关产品推荐
相关产品推荐

