You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在IntelliJ中运行OpenRewrite多模块项目单元测试报错求解决

在IntelliJ中运行OpenRewrite单元测试的类路径问题解决

问题场景

我在optaplanner-rewrite模块的单元测试中使用OpenRewrite BOM 1.11.0,测试代码如下:

@Override
public void defaults(RecipeSpec spec) {
    spec.recipe(new AsConstraintBuilder())
            .parser(JavaParser.fromJavaVersion()
                    .classpath("optaplanner-core"));
}

该测试在Maven中运行正常,但在IntelliJ中运行时抛出异常:

java.lang.IllegalArgumentException: Unable to find runtime dependencies beginning with: 'optaplanner-core'

    at org.openrewrite.java.JavaParser.dependenciesFromClasspath(JavaParser.java:97)
    at org.openrewrite.java.JavaParser$Builder.classpath(JavaParser.java:250)

原因是当前IDE打开了包含optaplanner-core和optaplanner-rewrite的多模块项目,测试运行的类路径中没有optaplanner-core.jar,仅存在optaplanner-core/target/classes目录。

解决方案

方法1:使用模块全限定坐标匹配

OpenRewrite的classpath()方法支持通过Maven坐标(groupId:artifactId)匹配依赖,无论类路径中是Jar包还是编译输出目录,都能正确识别。修改测试代码:

@Override
public void defaults(RecipeSpec spec) {
    spec.recipe(new AsConstraintBuilder())
            .parser(JavaParser.fromJavaVersion()
                    .classpath("org.optaplanner:optaplanner-core"));
}

这是最可靠的通用方案,适配Maven和IDE两种运行环境。

方法2:直接指定编译输出目录

如果只是临时适配IDE环境,可以直接指定optaplanner-core的编译输出目录:

@Override
public void defaults(RecipeSpec spec) {
    spec.recipe(new AsConstraintBuilder())
            .parser(JavaParser.fromJavaVersion()
                    .classpath("optaplanner-core/target/classes"));
}

注意:这种写法依赖项目的目录结构,不够灵活,不推荐长期使用。

方法3:调整IntelliJ测试运行配置

手动修改测试的类路径配置:

  • 点击运行按钮旁的下拉箭头,选择「Edit Configurations...」
  • 在「Configuration」标签页中,点击「Modify options」,勾选「Include dependencies with 'Provided' scope」(若optaplanner-core为provided依赖)
  • 或直接点击「Add」按钮,手动添加optaplanner-core模块的target/classes目录到类路径
  • 保存配置后重新运行测试

方法4:重新同步Maven项目

若IDE类路径同步异常:

  • 打开IntelliJ右侧的「Maven」面板
  • 点击顶部的「Reload All Maven Projects」刷新按钮
  • 等待同步完成后重新执行测试

内容的提问来源于stack exchange,提问作者Geoffrey De Smet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 03:51:05