diff --git a/src/main/java/org/openrewrite/java/testing/mockito/AnyStringToNullable.java b/src/main/java/org/openrewrite/java/testing/mockito/AnyStringToNullable.java index 407834f56..9b4f0fece 100644 --- a/src/main/java/org/openrewrite/java/testing/mockito/AnyStringToNullable.java +++ b/src/main/java/org/openrewrite/java/testing/mockito/AnyStringToNullable.java @@ -20,8 +20,9 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.JavaParser; +import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.MethodMatcher; -import org.openrewrite.java.PartProvider; import org.openrewrite.java.search.UsesMethod; import org.openrewrite.java.tree.J; @@ -32,8 +33,6 @@ */ public class AnyStringToNullable extends Recipe { private static final MethodMatcher ANY_STRING = new MethodMatcher("org.mockito.Mockito anyString()"); - private static final String MOCKITO_CLASS_PATH = "mockito-core-3.12"; - private static J.MethodInvocation nullableStringMethodTemplate = null; @Override public String getDisplayName() { @@ -53,31 +52,20 @@ public Duration getEstimatedEffortPerOccurrence() { @Override public TreeVisitor getVisitor() { return Preconditions.check(new UsesMethod<>(ANY_STRING), new JavaIsoVisitor() { - @Override public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { J.MethodInvocation mi = super.visitMethodInvocation(method, ctx); - if (ANY_STRING.matches(mi)) { maybeAddImport("org.mockito.ArgumentMatchers", "nullable", false); maybeRemoveImport("org.mockito.Mockito.anyString"); - return getNullableMethodTemplate().withPrefix(mi.getPrefix()); + return JavaTemplate.builder("nullable(String.class)") + .javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "mockito-core-3.12")) + .staticImports("org.mockito.ArgumentMatchers.nullable") + .build() + .apply(getCursor(), mi.getCoordinates().replace()); } return mi; } }); } - - private static J.MethodInvocation getNullableMethodTemplate() { - if (nullableStringMethodTemplate == null) { - nullableStringMethodTemplate = PartProvider.buildPart("import static org.mockito.ArgumentMatchers" + - ".nullable;\n" + - "public class A {\n" + - " void method() {\n" + - " Object x = nullable(String.class);\n" + - " }\n" + - "}", J.MethodInvocation.class, MOCKITO_CLASS_PATH); - } - return nullableStringMethodTemplate; - } } diff --git a/src/test/java/org/openrewrite/java/testing/mockito/AnyStringToNullableTest.java b/src/test/java/org/openrewrite/java/testing/mockito/AnyStringToNullableTest.java index 461f06547..842a327e5 100755 --- a/src/test/java/org/openrewrite/java/testing/mockito/AnyStringToNullableTest.java +++ b/src/test/java/org/openrewrite/java/testing/mockito/AnyStringToNullableTest.java @@ -24,7 +24,6 @@ import static org.openrewrite.java.Assertions.java; class AnyStringToNullableTest implements RewriteTest { - @Override public void defaults(RecipeSpec spec) { spec