且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 9 + maven + junit:测试代码是否需要自己的 module-info.java 以及将它放在哪里?

更新时间:2022-06-12 22:59:47

模块系统不区分生产代码和测试代码,所以如果选择模块化测试代码,prod.module并且 test.module 不能共享相同的包 com.acme.project,如 规格:

The module system does not distinguish between production code and test code, so if you choose to modularize test code, the prod.module and the test.module cannot share the same package com.acme.project, as described in the specs:

无干扰 — Java 编译器、虚拟机和运行时系统必须确保包含同名包的模块不会相互干扰.如果两个不同的模块包含同名的包,那么从每个模块的角度来看,该包中的所有类型和成员都仅由该模块定义.一个模块中该包中的代码不能访问另一个模块中该包中的包私有类型或成员.

Non-interference — The Java compiler, virtual machine, and run-time system must ensure that modules that contain packages of the same name do not interfere with each other. If two distinct modules contain packages of the same name then, from the perspective of each module, all of the types and members in that package are defined only by that module. Code in that package in one module must not be able to access package-private types or members in that package in the other module.

Alan Bateman 指出,Maven 编译器插件使用 --patch-module 和其他选项由模块系统在编译 src/test/java 树中的代码时提供,以便被测模块用测试类进行扩充.这也是在运行测试类时由 Surefire 插件完成的(参见 Support running unit tests in命名的 Java 9 模块).这意味着您无需将测试代码放在模块中.

As indicated by Alan Bateman, the Maven compiler plugin uses --patch-module and other options provided by the module system when compiling code in the src/test/java tree, so that the module under test is augmented with the test classes. And this is also done by the Surefire plugin when running the test classes (see Support running unit tests in named Java 9 modules). This means you don't need to place your test code in a module.