diff --git a/src/main/java/org/openrewrite/java/testing/arquillian/ReplaceArquillianInSequenceAnnotation.java b/src/main/java/org/openrewrite/java/testing/arquillian/ReplaceArquillianInSequenceAnnotation.java index 789cf5e5a..a869828a7 100644 --- a/src/main/java/org/openrewrite/java/testing/arquillian/ReplaceArquillianInSequenceAnnotation.java +++ b/src/main/java/org/openrewrite/java/testing/arquillian/ReplaceArquillianInSequenceAnnotation.java @@ -26,6 +26,9 @@ import org.openrewrite.java.tree.J; import java.util.Comparator; +import java.util.List; + +import static java.util.Collections.singletonList; public class ReplaceArquillianInSequenceAnnotation extends Recipe { private static final String IN_SEQUENCE = "org.jboss.arquillian.junit.InSequence"; @@ -40,17 +43,16 @@ public class ReplaceArquillianInSequenceAnnotation extends Recipe { @Getter final String description = "Transforms the Arquillian JUnit 4 `@InSequence` to the JUnit Jupiter `@Order`."; + @Override + public List getRecipeList() { + return singletonList(new ChangeType(IN_SEQUENCE, "org.junit.jupiter.api.Order", true)); + } + @Override public TreeVisitor getVisitor() { return Preconditions.check( - new UsesType<>("org.jboss.arquillian.junit.InSequence", false), + new UsesType<>(IN_SEQUENCE, false), new JavaIsoVisitor() { - @Override - public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { - doAfterVisit(new ChangeType(IN_SEQUENCE, "org.junit.jupiter.api.Order", true).getVisitor()); - return super.visitClassDeclaration(classDecl, ctx); - } - @Override public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) { J.MethodDeclaration m = super.visitMethodDeclaration(method, ctx); diff --git a/src/main/java/org/openrewrite/java/testing/assertj/JUnitFailToAssertJFail.java b/src/main/java/org/openrewrite/java/testing/assertj/JUnitFailToAssertJFail.java index 6b1d2dd58..1d86c2ea3 100644 --- a/src/main/java/org/openrewrite/java/testing/assertj/JUnitFailToAssertJFail.java +++ b/src/main/java/org/openrewrite/java/testing/assertj/JUnitFailToAssertJFail.java @@ -81,7 +81,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu .apply(getCursor(), mi.getCoordinates().replace(), args.toArray()); } - doAfterVisit(new RemoveUnusedImports().getVisitor()); + maybeRemoveImport(JUNIT); doAfterVisit(new UnqualifiedMethodInvocations()); return mi; } diff --git a/src/main/java/org/openrewrite/java/testing/jmockit/JMockitMockUpToMockito.java b/src/main/java/org/openrewrite/java/testing/jmockit/JMockitMockUpToMockito.java index 81740b3b6..a3e604828 100644 --- a/src/main/java/org/openrewrite/java/testing/jmockit/JMockitMockUpToMockito.java +++ b/src/main/java/org/openrewrite/java/testing/jmockit/JMockitMockUpToMockito.java @@ -302,7 +302,9 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl maybeRemoveImport(JMOCKIT_MOCKUP_IMPORT); maybeAddImport(MOCKITO_ALL_IMPORT.replace(".*", ""), "*", false); - doAfterVisit(new LambdaBlockToExpression().getVisitor()); + if (md != methodDecl) { + md = (J.MethodDeclaration) new LambdaBlockToExpression().getVisitor().visitNonNull(md, ctx, getCursor().getParentOrThrow()); + } doAfterVisit(ShortenFullyQualifiedTypeReferences.modifyOnly(md)); return maybeAutoFormat(methodDecl, md, ctx); } diff --git a/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java b/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java index b9614b01b..56fc7fccb 100644 --- a/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java +++ b/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java @@ -67,7 +67,6 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl if (m.getBody() == null) { return m; } - doAfterVisit(new LambdaBlockToExpression().getVisitor()); return m.withBody(m.getBody().withStatements(ListUtils.flatMap(m.getBody().getStatements(), methodStatement -> { J statementToCheck = methodStatement; final J.VariableDeclarations assertThrowsWithVarDec; @@ -136,6 +135,9 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl return argument; }) ); + if (getCursor().firstEnclosing(J.CompilationUnit.class) != null) { + newAssertThrows = (J.MethodInvocation) new LambdaBlockToExpression().getVisitor().visitNonNull(newAssertThrows, ctx, getCursor()); + } if (assertThrowsWithVarDec == null) { variableAssignments.add(newAssertThrows); diff --git a/src/main/java/org/openrewrite/java/testing/junit5/AssertToAssertions.java b/src/main/java/org/openrewrite/java/testing/junit5/AssertToAssertions.java index 50834cdf7..8f13638bd 100644 --- a/src/main/java/org/openrewrite/java/testing/junit5/AssertToAssertions.java +++ b/src/main/java/org/openrewrite/java/testing/junit5/AssertToAssertions.java @@ -29,8 +29,11 @@ import org.openrewrite.java.tree.*; import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; +import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toList; public class AssertToAssertions extends Recipe { @@ -48,6 +51,7 @@ public TreeVisitor getVisitor() { public static class AssertToAssertionsVisitor extends JavaIsoVisitor { private static final JavaType ASSERTION_TYPE = JavaType.buildType("org.junit.Assert"); + private static final String ASSERT_METHOD_NAMES = "assertMethodNames"; private static final MethodMatcher ASSERT_MATCHER = new MethodMatcher("org.junit.Assert *(..)"); private static final MethodMatcher ASSERT_THAT_MATCHER = new MethodMatcher("org.junit.Assert assertThat(..)"); private static final MethodMatcher ASSERT_SAME_OR_NOT_SAME_MATCHER = new MethodMatcher("org.junit.Assert assert*Same(*, *)"); @@ -88,9 +92,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu if (!isJunitAssertMethod(m)) { return m; } - doAfterVisit(new ChangeMethodTargetToStatic("org.junit.Assert " + m.getSimpleName() + "(..)", - "org.junit.jupiter.api.Assertions", null, null, true) - .getVisitor()); + changeTargetToAssertions(m.getSimpleName()); List> args = m.getPadding().getArguments().getPadding().getElements(); Expression firstArg = args.get(0).getElement(); @@ -142,13 +144,25 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu public J.MemberReference visitMemberReference(J.MemberReference memberRef, ExecutionContext ctx) { J.MemberReference mr = super.visitMemberReference(memberRef, ctx); if (isJunitAssertMethod(mr)) { - doAfterVisit(new ChangeMethodTargetToStatic("org.junit.Assert " + mr.getReference().getSimpleName() + "(..)", - "org.junit.jupiter.api.Assertions", null, null, true) - .getVisitor()); + changeTargetToAssertions(mr.getReference().getSimpleName()); } return mr; } + @Override + public J postVisit(J tree, ExecutionContext ctx) { + if (tree instanceof JavaSourceFile) { + for (String methodName : getCursor().>getMessage(ASSERT_METHOD_NAMES, emptySet())) { + doAfterVisit(new ChangeMethodTargetToStatic("org.junit.Assert " + methodName + "(..)", "org.junit.jupiter.api.Assertions", null, null, true).getVisitor()); + } + } + return tree; + } + + private void changeTargetToAssertions(String methodName) { + getCursor().dropParentUntil(JavaSourceFile.class::isInstance).computeMessageIfAbsent(ASSERT_METHOD_NAMES, k -> new LinkedHashSet()).add(methodName); + } + private static boolean isJunitAssertMethod(MethodCall call) { return ASSERT_MATCHER.matches(call) && !ASSERT_THAT_MATCHER.matches(call); } diff --git a/src/main/java/org/openrewrite/java/testing/junit5/ExpectedExceptionToAssertThrows.java b/src/main/java/org/openrewrite/java/testing/junit5/ExpectedExceptionToAssertThrows.java index 1cbfd9f15..081d1167d 100644 --- a/src/main/java/org/openrewrite/java/testing/junit5/ExpectedExceptionToAssertThrows.java +++ b/src/main/java/org/openrewrite/java/testing/junit5/ExpectedExceptionToAssertThrows.java @@ -79,10 +79,6 @@ private static class ExpectedExceptionToAssertThrowsVisitor extends JavaIsoVisit @Override public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx); - // Only a migrated method can have produced the lambda that needs collapsing. - if (cd != classDecl) { - doAfterVisit(new LambdaBlockToExpression().getVisitor()); - } // A method that could not be migrated still needs the rule, so leave the field and its imports in place. boolean cannotMigrate = getCursor().getMessage(CANNOT_MIGRATE) != null; @@ -197,6 +193,7 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) { maybeAddImport("org.junit.jupiter.api.Assertions", "assertThrows", false); Statement firstExpectedExceptionMethodInvocation = getCursor().getMessage(FIRST_EXPECTED_EXCEPTION_METHOD_INVOCATION); + int assertThrowsIndex = b.getStatements().indexOf(firstExpectedExceptionMethodInvocation); String templateString = exceptionClass instanceof String ? "#{}assertThrows(#{}, () -> #{any()});" : "#{}assertThrows(#{any()}, () -> #{any()});"; b = JavaTemplate.builder(templateString) .javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "junit-jupiter-api-5", "hamcrest-3")) @@ -239,6 +236,7 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) { } return removeStatement.get() ? null : statement; })); + b = b.withStatements(ListUtils.map(b.getStatements(), (i, statement) -> i == assertThrowsIndex ? (Statement) new LambdaBlockToExpression().getVisitor().visitNonNull(statement, ctx, updateCursor) : statement)); Statement lastStatement = b.getStatements().get(b.getStatements().size() - 1); if (!findSuccessorStatements(new Cursor(updateCursor(b), lastStatement)).isEmpty()) { J.Return returnStatement = new J.Return(randomId(), b.getStatements().get(b.getStatements().size() - 1).getPrefix().withComments(emptyList()), Markers.EMPTY, null); diff --git a/src/main/java/org/openrewrite/java/testing/junit5/JUnitParamsRunnerToParameterized.java b/src/main/java/org/openrewrite/java/testing/junit5/JUnitParamsRunnerToParameterized.java index 1b019461d..2917752d0 100644 --- a/src/main/java/org/openrewrite/java/testing/junit5/JUnitParamsRunnerToParameterized.java +++ b/src/main/java/org/openrewrite/java/testing/junit5/JUnitParamsRunnerToParameterized.java @@ -208,8 +208,7 @@ public ParametersNoArgsImplicitMethodSource(Set initMethods, Map methodNames = getCursor().getMessage(MakeMethodStatic.REFERENCED_METHODS, emptyList()); if (cd.getType() != null && !methodNames.isEmpty()) { doAfterVisit(new MakeMethodStatic(cd.getType(), methodNames)); diff --git a/src/main/java/org/openrewrite/java/testing/junit5/RemoveObsoleteRunners.java b/src/main/java/org/openrewrite/java/testing/junit5/RemoveObsoleteRunners.java index cb48f2a04..b50ef9bb8 100644 --- a/src/main/java/org/openrewrite/java/testing/junit5/RemoveObsoleteRunners.java +++ b/src/main/java/org/openrewrite/java/testing/junit5/RemoveObsoleteRunners.java @@ -18,8 +18,9 @@ import lombok.EqualsAndHashCode; import lombok.Value; import org.openrewrite.*; +import org.openrewrite.java.AnnotationMatcher; import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.RemoveAnnotation; +import org.openrewrite.java.RemoveAnnotationVisitor; import org.openrewrite.java.search.UsesType; import org.openrewrite.java.tree.J; @@ -49,12 +50,13 @@ public class RemoveObsoleteRunnersVisitor extends JavaIsoVisitor getVisitor() { new UsesType<>("org.junit.After", false), new UsesType<>("org.junit.AfterClass", false) ), - new UpdateBeforeAfterAnnotationsVisitor()); + new RemoveRedundantJUnit4LifecycleAnnotations()); } - public static class UpdateBeforeAfterAnnotationsVisitor extends JavaIsoVisitor { - - @Override - public J preVisit(J tree, ExecutionContext ctx) { - stopAfterPreVisit(); - // Remove the JUnit 4 annotation where the Jupiter equivalent is already present, to avoid creating a - // duplicate annotation when the type is subsequently changed below. - doAfterVisit(new RemoveRedundantJUnit4LifecycleAnnotations()); - JUNIT4_TO_JUPITER.forEach((from, to) -> doAfterVisit(new ChangeType(from, to, true).getVisitor())); - return tree; - } + @Override + public List getRecipeList() { + return JUNIT4_TO_JUPITER.entrySet().stream().map(e -> new ChangeType(e.getKey(), e.getValue(), true)).collect(toList()); } private static class RemoveRedundantJUnit4LifecycleAnnotations extends JavaIsoVisitor { diff --git a/src/main/java/org/openrewrite/java/testing/junit5/UseWiremockExtension.java b/src/main/java/org/openrewrite/java/testing/junit5/UseWiremockExtension.java index 1c55db875..292283709 100644 --- a/src/main/java/org/openrewrite/java/testing/junit5/UseWiremockExtension.java +++ b/src/main/java/org/openrewrite/java/testing/junit5/UseWiremockExtension.java @@ -25,6 +25,10 @@ import org.openrewrite.java.search.UsesType; import org.openrewrite.java.tree.*; +import java.util.List; + +import static java.util.Collections.singletonList; + public class UseWiremockExtension extends Recipe { private static final String WIREMOCK_RULE = "com.github.tomakehurst.wiremock.junit.WireMockRule"; @@ -39,18 +43,14 @@ public class UseWiremockExtension extends Recipe { @Getter final String description = "As of 2.31.0, wiremock [supports JUnit 5](https://wiremock.org/docs/junit-jupiter/) via an extension."; + @Override + public List getRecipeList() { + return singletonList(new ChangeType(WIREMOCK_RULE, WIREMOCK_EXTENSION, true)); + } + @Override public TreeVisitor getVisitor() { return Preconditions.check(new UsesType<>(WIREMOCK_RULE, false), new JavaVisitor() { - - @Override - public J preVisit(J tree, ExecutionContext ctx) { - if (tree instanceof JavaSourceFile) { - doAfterVisit(new ChangeType(WIREMOCK_RULE, WIREMOCK_EXTENSION, true).getVisitor()); - } - return tree; - } - @Override public J visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) { J.VariableDeclarations vd = (J.VariableDeclarations) super.visitVariableDeclarations(multiVariable, ctx); diff --git a/src/main/java/org/openrewrite/java/testing/mockito/MockUtilsToStatic.java b/src/main/java/org/openrewrite/java/testing/mockito/MockUtilsToStatic.java index c09dad648..781be43ee 100644 --- a/src/main/java/org/openrewrite/java/testing/mockito/MockUtilsToStatic.java +++ b/src/main/java/org/openrewrite/java/testing/mockito/MockUtilsToStatic.java @@ -24,6 +24,10 @@ import org.openrewrite.java.search.UsesType; import org.openrewrite.java.tree.J; +import java.util.List; + +import static java.util.Collections.singletonList; + /** * In Mockito 1 you use a code snippet like: *

@@ -44,6 +48,11 @@ public class MockUtilsToStatic extends Recipe { @Getter final String description = "Best-effort attempt to remove Mockito `MockUtil` instances."; + @Override + public List getRecipeList() { + return singletonList(new ChangeMethodTargetToStatic("org.mockito.internal.util.MockUtil *(..)", "org.mockito.internal.util.MockUtil", null, null, false)); + } + @Override public TreeVisitor getVisitor() { return Preconditions.check(new UsesType<>("org.mockito.internal.util.MockUtil", false), new MockUtilsToStaticVisitor()); @@ -51,13 +60,6 @@ public TreeVisitor getVisitor() { public static class MockUtilsToStaticVisitor extends JavaVisitor { private static final MethodMatcher METHOD_MATCHER = new MethodMatcher("org.mockito.internal.util.MockUtil ()"); - private final ChangeMethodTargetToStatic changeMethodTargetToStatic = new ChangeMethodTargetToStatic("org.mockito.internal.util.MockUtil *(..)", "org.mockito.internal.util.MockUtil", null, null, false); - - @Override - public J visitCompilationUnit(J.CompilationUnit compilationUnit, ExecutionContext ctx) { - J.CompilationUnit cu = (J.CompilationUnit) super.visitCompilationUnit(compilationUnit, ctx); - return (J.CompilationUnit) changeMethodTargetToStatic.getVisitor().visitNonNull(cu, ctx); - } @Override public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) { diff --git a/src/main/java/org/openrewrite/java/testing/mockito/RemoveDoNothingForDefaultMocks.java b/src/main/java/org/openrewrite/java/testing/mockito/RemoveDoNothingForDefaultMocks.java index 0b86fbaf7..5318c2b09 100644 --- a/src/main/java/org/openrewrite/java/testing/mockito/RemoveDoNothingForDefaultMocks.java +++ b/src/main/java/org/openrewrite/java/testing/mockito/RemoveDoNothingForDefaultMocks.java @@ -24,12 +24,12 @@ import org.openrewrite.java.AnnotationMatcher; import org.openrewrite.java.JavaIsoVisitor; import org.openrewrite.java.MethodMatcher; -import org.openrewrite.java.RemoveUnusedImports; import org.openrewrite.java.search.UsesMethod; import org.openrewrite.java.tree.Expression; import org.openrewrite.java.tree.J; import org.openrewrite.java.tree.JavaType; import org.openrewrite.java.tree.Statement; +import org.openrewrite.java.tree.TypeUtils; import java.util.HashSet; import java.util.List; @@ -159,7 +159,7 @@ public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations if (value instanceof J.Lambda || value instanceof J.Case && ((J.Case) value).getStatements().isEmpty()) { return mi; } - doAfterVisit(new RemoveUnusedImports().getVisitor()); + typesReferencedBy(mi).forEach(this::maybeRemoveImport); return null; } return mi; @@ -215,4 +215,18 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Atomi } ); } + + private static Set typesReferencedBy(J tree) { + return new JavaIsoVisitor>() { + @Override + public @Nullable JavaType visitType(@Nullable JavaType javaType, Set types) { + JavaType owner = javaType instanceof JavaType.Method ? ((JavaType.Method) javaType).getDeclaringType() : javaType instanceof JavaType.Variable ? ((JavaType.Variable) javaType).getOwner() : javaType; + JavaType.FullyQualified type = TypeUtils.asFullyQualified(owner); + if (type != null) { + types.add(type.getFullyQualifiedName()); + } + return javaType; + } + }.reduce(tree, new HashSet<>()); + } }