2020import org .openrewrite .Recipe ;
2121import org .openrewrite .TreeVisitor ;
2222import org .openrewrite .java .JavaIsoVisitor ;
23+ import org .openrewrite .java .JavaParser ;
24+ import org .openrewrite .java .JavaTemplate ;
2325import org .openrewrite .java .MethodMatcher ;
24- import org .openrewrite .java .PartProvider ;
2526import org .openrewrite .java .search .UsesMethod ;
2627import org .openrewrite .java .tree .J ;
2728
3233 */
3334public class AnyStringToNullable extends Recipe {
3435 private static final MethodMatcher ANY_STRING = new MethodMatcher ("org.mockito.Mockito anyString()" );
35- private static final String MOCKITO_CLASS_PATH = "mockito-core-3.12" ;
36- private static J .MethodInvocation nullableStringMethodTemplate = null ;
3736
3837 @ Override
3938 public String getDisplayName () {
@@ -53,31 +52,20 @@ public Duration getEstimatedEffortPerOccurrence() {
5352 @ Override
5453 public TreeVisitor <?, ExecutionContext > getVisitor () {
5554 return Preconditions .check (new UsesMethod <>(ANY_STRING ), new JavaIsoVisitor <ExecutionContext >() {
56-
5755 @ Override
5856 public J .MethodInvocation visitMethodInvocation (J .MethodInvocation method , ExecutionContext ctx ) {
5957 J .MethodInvocation mi = super .visitMethodInvocation (method , ctx );
60-
6158 if (ANY_STRING .matches (mi )) {
6259 maybeAddImport ("org.mockito.ArgumentMatchers" , "nullable" , false );
6360 maybeRemoveImport ("org.mockito.Mockito.anyString" );
64- return getNullableMethodTemplate ().withPrefix (mi .getPrefix ());
61+ return JavaTemplate .builder ("nullable(String.class)" )
62+ .javaParser (JavaParser .fromJavaVersion ().classpathFromResources (ctx , "mockito-core-3.12" ))
63+ .staticImports ("org.mockito.ArgumentMatchers.nullable" )
64+ .build ()
65+ .apply (getCursor (), mi .getCoordinates ().replace ());
6566 }
6667 return mi ;
6768 }
6869 });
6970 }
70-
71- private static J .MethodInvocation getNullableMethodTemplate () {
72- if (nullableStringMethodTemplate == null ) {
73- nullableStringMethodTemplate = PartProvider .buildPart ("import static org.mockito.ArgumentMatchers" +
74- ".nullable;\n " +
75- "public class A {\n " +
76- " void method() {\n " +
77- " Object x = nullable(String.class);\n " +
78- " }\n " +
79- "}" , J .MethodInvocation .class , MOCKITO_CLASS_PATH );
80- }
81- return nullableStringMethodTemplate ;
82- }
8371}
0 commit comments