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

OpenRewrite:如何在JUnit测试Recipe时启用本地Maven仓库?

解决OpenRewrite JUnit测试中本地SNAPSHOT依赖解析失败问题

核心原因

OpenRewrite测试环境的默认依赖解析配置不会自动读取本地Maven仓库,导致仅存于本地的SNAPSHOT依赖无法被识别,触发错误注释插入逻辑。

解决方案

1. 配置测试专用Maven设置文件

在测试资源目录(如src/test/resources)下创建settings.xml,明确指定本地仓库路径:

<settings>
  <localRepository>${user.home}/.m2/repository</localRepository>
  <mirrors>
    <mirror>
      <id>central</id>
      <mirrorOf>central</mirrorOf>
      <url>https://repo1.maven.org/maven2</url>
    </mirror>
  </mirrors>
</settings>

2. 在测试类中加载自定义配置

在你的Recipe测试类中,通过MavenSettings加载上述配置,覆盖默认解析规则:

import org.openrewrite.maven.MavenSettings;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

public class YourDependencyRewriteRecipeTest implements RewriteTest {
    @Override
    public void defaults(RecipeSpec spec) {
        MavenSettings customSettings = MavenSettings.builder()
            .settingsPath("src/test/resources/settings.xml")
            .build();
        
        spec.recipe(new YourDependencyRewriteRecipe())
            .mavenSettings(customSettings);
    }

    // 编写具体测试用例...
}

3. 临时禁用依赖验证(仅用于逻辑测试)

若仅需验证Recipe的改写逻辑,无需校验依赖有效性,可关闭依赖解析校验:

@Override
public void defaults(RecipeSpec spec) {
    spec.recipe(new YourDependencyRewriteRecipe())
        .maven(mavenConfig -> mavenConfig.resolveDependencies(false));
}

注意:此方案跳过依赖有效性校验,仅适合快速验证改写逻辑,不推荐用于完整功能测试。

内容的提问来源于stack exchange,提问作者Lukáš Petrovický

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:35:07