在这个项目中,我有一个模块化的设置。有一个父级,其中有两个模块。
这是来自parent-pom.xml的摘录:
<modules>
<module>moduleA</module>
<module>moduleB</module>
</modules>
两个模块都有一个module-info.java。这是moduleB的module-info.java:
module moduleB {
requires spring.web;
requires static lombok;
requires java.validation;
requires swagger.annotations;
requires slf4j.api;
exports com.example.service
}
在moduleB中,有一个主文件夹和一个test文件夹,就像任何常规的Java项目一样。在测试文件夹中,有一个JUnit5测试,该测试试图测试同一包中但在src文件夹中的服务。
[尝试尝试执行此操作时,出现以下错误消息:
module moduleB does not "opens com.example.service" to unnamed module @67205a84
据我了解,所有不属于模块的依赖项都将打包在一个“未命名”模块中。在这种情况下,模块为@ 67205a84。我希望在该模块中放的东西是Mockito之类的东西,我仅将其用于测试。如果我对此假设有误,请纠正我。
当我打开我的模块B时(通过在模块声明之前添加单词“ open”),测试运行顺利。但这显然不是我想要的。
所以我的问题确实是:我可以打开未命名的模块以便可以运行我的测试,但是除了测试之外,我的模块保持关闭状态吗?
这里是目录结构的简化概述。
- parent
|
-> - pom.xml
- moduleA
- moduleB
|
-> - pom.xml
- src
|
-> - main
|
-> - java
|
-> - module.info
- com.example.service
|
-> - ModuleBService.java
- test
|
-> - java
|
-> - com.example
|
-> - Application.java
- com.example.service
|
-> - ModuleBServiceTest.java
事实证明,Application.class的位置是相关的。我要测试的模块没有用@SpringbootApplication注释的类,因为它只是一个库。为了测试它的功能,我必须在测试中启动一个SpringbootApplication。当Application.java与ModuleBServiceTest.java位于同一程序包中时,一切都很好。当我将其移出另一个包装时,会发生上述错误消息。为什么会这样?
您所要做的是配置surefire插件以将模块打开到moduleB
的POM中未命名的模块>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
<!-- Allow access to the tests during test time -->
--add-opens moduleB/com.example.service=ALL-UNNAMED
<!-- Add export to test-util classes to moduleC if it wants to reuse these -->
--add-exports moduleB/com.example.service.test.util=moduleC
<!-- Prevent any illegal access to modules -->
--illegal-access=deny
</argLine>
</configuration>
</plugin>
</plugins>
</build>