
在 OpenRewrite 的 JUnit 测试中,若 Recipe 涉及依赖版本(如 @@@SNAPSHOT@@@)需从本地 Maven 仓库解析,必须显式配置 MavenRepository,否则默认仅尝试中央仓库(repo.maven.apache.org),导致解析失败并插入错误注释。
在 openrewrite 的 junit 测试中,若 recipe 涉及依赖版本(如 `@@@snapshot@@@`)需从本地 maven 仓库解析,必须显式配置 `mavenrepository`,否则默认仅尝试中央仓库(`repo.maven.apache.org`),导致解析失败并插入错误注释。
OpenRewrite 在测试环境中(如 rewriteRun())默认不自动加载本地 Maven 仓库(~/.m2/repository),其依赖解析器仅按 ExecutionContext 中显式声明的仓库列表进行查找。当你的 Recipe 将 <version>1.0.0</version> 替换为 <version>@@@SNAPSHOT@@@</version> 后,OpenRewrite 会尝试解析该坐标以校验 POM 合法性、推导传递依赖等——但若未配置对应仓库,它将失败,并像你所见那样注入 <!--~~(c:d:@@@SNAPSHOT@@@ failed...)~~>--> 注释。
✅ 正确做法是:在 rewriteRun() 的 spec 中,通过 MavenExecutionContextView 显式注入本地仓库 URI(即 file:// 协议路径)。以下是推荐实现:
@Test
void recipeWithLocalSnapshot() {
String localRepoPath = System.getProperty("user.home") + "/.m2/repository";
rewriteRun(
spec -> spec
.recipe(new YourRecipe()) // 替换为你的实际 Recipe 实例
.executionContext(
MavenExecutionContextView
.view(new InMemoryExecutionContext())
.setRepositories(List.of(
// 关键:添加本地仓库(使用 file:// 协议)
MavenRepository.builder()
.id("local")
.uri("file://" + localRepoPath)
.build(),
// 可选:同时保留中央仓库以支持其他依赖解析
MavenRepository.builder()
.id("central")
.uri("https://repo.maven.apache.org/maven2/")
.build()
))
),
pomXml(
"""
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>example</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>a</groupId>
<artifactId>b</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>
""",
"""
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>example</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>c</groupId>
<artifactId>d</artifactId>
<version>@@@SNAPSHOT@@@</version>
</dependency>
</dependencies>
</project>
"""
)
);
}⚠️ 注意事项:
提供端到端的高端代理设置和使用指导,包括代理类型选择、地区定向、访问配置、API密钥验证和监控。
-
路径协议必须为
file://:MavenRepository.uri()不接受相对路径或无协议路径;Windows 用户需确保路径使用正斜杠/或双反斜杠\,例如"file://C:/Users/Name/.m2/repository"。 -
仓库 ID 建议唯一且有意义(如
"local"),便于调试和避免冲突。 - 若本地 SNAPSHOT 依赖本身有父 POM 或 BOM,确保其也存在于本地仓库中,否则仍可能解析失败。
- 避免在测试中依赖
settings.xml或全局 Maven 配置——OpenRewrite 测试是隔离的,所有仓库必须显式声明。
? 进阶提示:如需复用配置,可封装为 ExecutionContext 工具方法;若项目使用 maven-invoker-plugin 或 CI 环境,建议将本地仓库路径设为系统属性或测试资源参数,提升可移植性。
通过上述方式,OpenRewrite 测试即可像真实 Maven 构建一样访问本地 SNAPSHOT,彻底消除解析失败注释,确保 Recipe 行为与生产环境一致。

















