在 Java 9 及以后版本中引入了 Java Platform Module System(JPMS),也就是常说的 Java Module(模块)。测试 Java Module 可以从编译、运行、单元测试、模块边界验证几个方面来进行。下面系统地说明。
demo/
├── src/
│ └── com.example.hello/
│ ├── module-info.java
│ └── com/example/hello/Hello.java
└── test/
└── com.example.hello/
└── com/example/hello/HelloTest.java
module com.example.hello {
exports com.example.hello;
}
package com.example.hello;
public class Hello {
public String say() {
return "Hello Module";
}
}
javac / java 测试模块(基础验证)javac -d out/src \
src/com.example.hello/module-info.java \
src/com.example.hello/com/example/hello/Hello.java
java --module-path out/src \
--module com.example.hello/com.example.hello.Hello
如果没有
main方法,可以单独写测试类或单元测试。
module com.example.hello {
exports com.example.hello;
requires junit.jupiter.api;
}
package com.example.hello;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class HelloTest {
@Test
void testSay() {
assertEquals("Hello Module", new Hello().say());
}
}
编译并运行:
javac -d out/test --module-path out/src:junit.jar \
test/com.example.hello/module-info.java \
test/com.example.hello/com/example/hello/HelloTest.java
java --module-path out/src:out/test:junit.jar \
--add-modules junit.platform.console \
org.junit.platform.console.ConsoleLauncher \
--select-package com.example.hello
hello-module/
├── pom.xml
└── src/
├── main/java/
│ ├── module-info.java
│ └── com/example/hello/Hello.java
└── test/java/
└── com/example/hello/HelloTest.java
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<release>17</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
</plugin>
mvn test
✅ Maven 会自动处理模块路径(module-path)
// 另一个模块尝试访问
import com.example.hello.Hello; // OK
import com.example.hello.internal.Secret; // 编译失败
--add-exports 临时测试java --add-exports com.example.hello/com.example.hello.internal=ALL-UNNAMED
⚠️ 仅用于测试,不建议生产使用
| 工具 | 是否支持 Module |
|---|---|
| JUnit 5 | ✅ |
| Maven | ✅ |
| Gradle | ✅(需 Java 9+) |
| Mockito | ✅(需要 opens) |
| JaCoCo | ✅ |
# 查看模块依赖
java --module-path out/src --list-modules
# 查看模块描述
java --describe-module com.example.hello
测试 Java Module 的核心方法:
javac + java 手动验证如果你有具体场景(如:Spring Boot + Module、微服务、老项目迁移),我可以给你更针对性的测试方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。