Gradle构建JavaFX项目中TestFX模块找不到问题求助
解决JavaFX Gradle项目中TestFX模块找不到的问题
问题根源
你把TestFX依赖放在testImplementation下,这意味着这些依赖仅在测试编译、运行阶段生效,主代码编译(src/main/java目录)时根本无法访问这些测试模块,所以主模块的module-info.java里声明requires org.testfx和requires org.testfx.junit5会报"module not found"。
修复步骤
1. 修正主模块的module-info.java
删除主模块中对TestFX模块的依赖声明,保留对控制器包的opens配置(测试时需要反射访问控制器类):
module org.example.swm { requires javafx.controls; requires javafx.fxml; requires javafx.web; requires org.controlsfx.controls; requires com.dlsc.formsfx; requires net.synedra.validatorfx; requires org.kordamp.ikonli.javafx; requires org.kordamp.bootstrapfx.core; requires eu.hansolo.tilesfx; // 保留这行,允许TestFX反射访问控制器 opens org.example.swm.controllers to javafx.fxml, org.testfx, org.testfx.junit5; exports org.example.swm; }
2. 为测试代码添加专属module-info.java
在src/test/java目录下创建module-info.java,声明测试所需的模块依赖:
module org.example.swm.test { // 依赖主模块 requires org.example.swm; // 依赖TestFX及JUnit5相关模块 requires org.testfx.core; requires org.testfx.junit5; requires org.junit.jupiter.api; // 允许TestFX和JUnit访问测试类 opens org.example.swm.controllers to org.testfx.junit5, org.junit.jupiter.api; }
3. 验证Gradle配置
你当前的依赖配置无需调整,testImplementation是TestFX依赖的正确声明方式,确保仅测试阶段可用:
dependencies { implementation('org.controlsfx:controlsfx:11.2.1') implementation('com.dlsc.formsfx:formsfx-core:11.6.0') { exclude(group: 'org.openjfx') } implementation('net.synedra:validatorfx:0.5.0') { exclude(group: 'org.openjfx') } implementation('org.kordamp.ikonli:ikonli-javafx:12.3.1') implementation('org.kordamp.bootstrapfx:bootstrapfx-core:0.4.0') implementation('eu.hansolo:tilesfx:21.0.3') { exclude(group: 'org.openjfx') } testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}") testImplementation("org.testfx:testfx-core:4.0.17") testImplementation("org.testfx:testfx-junit5:4.0.17") }
额外提示
- 如果IntelliJ仍有错误提示,除了Invalidate Caches,尝试点击Gradle面板的刷新按钮重新导入项目。
- 确保TestFX版本(4.0.17)与JavaFX版本兼容,该版本适配JavaFX 11及以上,符合你的依赖配置。
内容的提问来源于stack exchange,提问作者Haris Ali
相关产品推荐
相关产品推荐

