Java 9模块依赖自动模块时mvn test执行失败的解决咨询
解决Maven多模块项目中自动模块的测试依赖问题
问题根源
mvn test执行时,core模块还没走完打包流程(Maven默认生命周期里,test阶段比package阶段早),service作为Java9模块,无法识别未打包的core代码,因此抛出module not found: core错误。
无需将core转为Java9模块的解决办法
办法1:让core在service测试前完成打包
在service模块的POM里,配置maven-jar-plugin,强制core在service处理测试类阶段就完成打包:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <executions> <execution> <id>pre-test-core-package</id> <phase>process-test-classes</phase> <goals> <goal>jar</goal> </goals> <configuration> <skipIfEmpty>false</skipIfEmpty> </configuration> </execution> </executions> </plugin> </plugins> </build>
或者用maven-dependency-plugin把core的Jar复制到service的测试类目录下:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-core-jar</id> <phase>process-test-classes</phase> <goals> <goal>copy</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>你的项目groupId</groupId> <artifactId>core</artifactId> <version>项目版本号</version> <outputDirectory>${project.build.directory}/test-classes</outputDirectory> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build>
办法2:先将core安装到本地Maven仓库
要么手动先执行mvn install -DskipTests,把core的Jar安装到本地仓库后再跑mvn test;要么在父POM里配置,让service测试前自动执行core的install操作:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <executions> <execution> <id>install-core-first</id> <phase>pre-integration-test</phase> <goals> <goal>install</goal> </goals> <configuration> <skip>${skipTests}</skip> </configuration> </execution> </executions> </plugin> </plugins> </build>
办法3:给测试JVM添加参数,直接使用core的编译目录
在service模块的POM里,给maven-surefire-plugin添加JVM参数,把core的编译输出目录加到模块路径中,让Java9直接识别为自动模块:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine> --module-path ${project.build.outputDirectory}:${project.basedir}/../core/target/classes --add-modules core </argLine> </configuration> </plugin> </plugins> </build>
这个办法无需打包core,直接使用编译好的class文件目录,适合快速调试场景。
验证
按上述任意一种配置修改后,执行mvn test,service模块的测试应该能正常加载core自动模块,不再抛出module not found错误。
内容的提问来源于stack exchange,提问作者Aidan Do
相关产品推荐
相关产品推荐

