JUnit测试JavaFX项目时报java.lang.IllegalAccessError错误如何解决
问题根因
- JUnit 5版本不统一:pom中properties声明的
junit.version为5.7.1,但实际引入的junit-jupiter依赖版本为5.7.0,不同版本的JUnit组件在Java 17模块化环境下会出现跨包访问权限问题 - 缺少JUnit平台相关的测试依赖,仅引入junit-jupiter不足以支持IDEA的JUnit 5测试runner正常运行
- 未针对测试场景配置JVM模块化参数,Java 17强封装限制了JUnit内部类的跨模块访问
解决方案
步骤1:统一JUnit 5版本并补充完整测试依赖
修改pom.xml的dependencies节点,替换原有JUnit相关配置:
<!-- 统一使用properties中声明的junit.version --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <version>1.7.1</version> <scope>test</scope> </dependency>
步骤2:配置maven-surefire-plugin支持测试场景的模块化访问
在pom.xml的build/plugins节点下新增测试插件配置:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M7</version> <configuration> <argLine> --add-exports org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED --add-opens org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED </argLine> </configuration> </plugin>
步骤3:IDEA本地测试配置适配(直接在IDEA中运行测试用例时需要)
打开IDEA的测试运行配置,在VM options中添加以下参数:
--add-exports org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED --add-opens org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED
步骤4:修复测试用例语法错误
你当前的测试用例中assertEquals(12.99, d1);存在逻辑错误,第二个参数应该是对应价格的属性/方法返回值,不能直接传入d1对象,否则会触发类型匹配错误,参考修改:
// 修改后的断言语句,假设你的Deluxe类有返回价格的price()方法 assertEquals(12.99, d1.price());
内容的提问来源于stack exchange,提问作者Josh S.
相关产品推荐
相关产品推荐

