Skip to content

Commit 5724dda

Browse files
authored
Added EnclosedToNested recipe for JUnit4 to JUnit5 migration (#233)
Thanks @nmck257
1 parent ca6cf0a commit 5724dda

File tree

3 files changed

+281
-0
lines changed

3 files changed

+281
-0
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
/*
2+
* Copyright 2021 the original author or authors.
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.openrewrite.java.testing.junit5;
17+
18+
import lombok.EqualsAndHashCode;
19+
import lombok.Value;
20+
import org.jetbrains.annotations.NotNull;
21+
import org.openrewrite.ExecutionContext;
22+
import org.openrewrite.Recipe;
23+
import org.openrewrite.TreeVisitor;
24+
import org.openrewrite.java.JavaIsoVisitor;
25+
import org.openrewrite.java.JavaParser;
26+
import org.openrewrite.java.JavaTemplate;
27+
import org.openrewrite.java.format.AutoFormat;
28+
import org.openrewrite.java.format.AutoFormatVisitor;
29+
import org.openrewrite.java.search.FindAnnotations;
30+
import org.openrewrite.java.search.UsesType;
31+
import org.openrewrite.java.tree.J;
32+
import org.openrewrite.java.tree.JavaSourceFile;
33+
34+
import java.time.Duration;
35+
import java.util.Collections;
36+
import java.util.Comparator;
37+
import java.util.Set;
38+
39+
import static org.openrewrite.Parser.Input.fromString;
40+
41+
@Value
42+
@EqualsAndHashCode(callSuper = true)
43+
public class EnclosedToNested extends Recipe {
44+
private static final String ENCLOSED = "org.junit.experimental.runners.Enclosed";
45+
private static final String RUN_WITH = "org.junit.runner.RunWith";
46+
private static final String NESTED = "org.junit.jupiter.api.Nested";
47+
private static final String TEST_JUNIT4 = "org.junit.Test";
48+
private static final String TEST_JUNIT_JUPITER = "org.junit.jupiter.api.Test";
49+
50+
@Override
51+
public String getDisplayName() {
52+
return "JUnit 4 `@RunWith(Enclosed.class)` to JUnit Jupiter `@Nested`";
53+
}
54+
55+
@Override
56+
public String getDescription() {
57+
return "Removes the `Enclosed` specification from a class, and adds `Nested` to its inner classes";
58+
}
59+
60+
@Override
61+
public TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
62+
return new UsesType<>(ENCLOSED);
63+
}
64+
65+
@Override
66+
public Duration getEstimatedEffortPerOccurrence() {
67+
return Duration.ofMinutes(5);
68+
}
69+
70+
@Override
71+
public TreeVisitor<?, ExecutionContext> getVisitor() {
72+
return new JavaIsoVisitor<ExecutionContext>() {
73+
@SuppressWarnings("ConstantConditions")
74+
@Override
75+
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
76+
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
77+
final Set<J.Annotation> runWithEnclosedAnnotationSet = FindAnnotations.find(cd.withBody(null),
78+
String.format("@%s(%s.class)", RUN_WITH, ENCLOSED));
79+
for (J.Annotation runWithEnclosed : runWithEnclosedAnnotationSet) {
80+
cd.getLeadingAnnotations().remove(runWithEnclosed);
81+
cd = cd.withBody((J.Block) new AddNestedAnnotationVisitor().visit(cd.getBody(), ctx, getCursor()));
82+
83+
maybeRemoveImport(ENCLOSED);
84+
maybeRemoveImport(RUN_WITH);
85+
maybeAddImport(NESTED);
86+
}
87+
return cd;
88+
}
89+
};
90+
}
91+
92+
public static class AddNestedAnnotationVisitor extends JavaIsoVisitor<ExecutionContext> {
93+
@Override
94+
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
95+
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
96+
if (hasTestMethods(cd)) {
97+
cd = cd.withTemplate(getNestedJavaTemplate(), cd.getCoordinates().addAnnotation(Comparator.comparing(
98+
J.Annotation::getSimpleName)));
99+
cd.getModifiers().removeIf(modifier -> modifier.getType().equals(J.Modifier.Type.Static));
100+
}
101+
return cd;
102+
}
103+
104+
@NotNull
105+
private JavaTemplate getNestedJavaTemplate() {
106+
return JavaTemplate.builder(this::getCursor, "@Nested")
107+
.javaParser(() -> JavaParser.fromJavaVersion().dependsOn(Collections.singletonList(
108+
fromString("package org.junit.jupiter.api;\npublic @interface Nested {}"))).build())
109+
.imports(NESTED).build();
110+
}
111+
112+
private boolean hasTestMethods(final J.ClassDeclaration cd) {
113+
return !FindAnnotations.find(cd, "@" + TEST_JUNIT4).isEmpty()
114+
|| !FindAnnotations.find(cd, "@" + TEST_JUNIT_JUPITER).isEmpty();
115+
}
116+
}
117+
}

src/main/resources/META-INF/rewrite/junit5.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ recipeList:
8080
- org.openrewrite.java.testing.junit5.ExpectedExceptionToAssertThrows
8181
- org.openrewrite.java.testing.junit5.UpdateMockWebServer
8282
- org.openrewrite.java.testing.junit5.VertxUnitToVertxJunit5
83+
- org.openrewrite.java.testing.junit5.EnclosedToNested
8384
- org.openrewrite.java.testing.hamcrest.AddHamcrestIfUsed
8485
- org.openrewrite.maven.RemoveDependency:
8586
groupId: junit
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
package org.openrewrite.java.testing.junit5
2+
3+
import org.junit.jupiter.api.Test
4+
import org.openrewrite.java.JavaParser
5+
import org.openrewrite.test.RecipeSpec
6+
import org.openrewrite.test.RewriteTest
7+
8+
class EnclosedToNestedTest : RewriteTest {
9+
override fun defaults(spec: RecipeSpec) {
10+
spec.recipe(EnclosedToNested())
11+
.parser(JavaParser.fromJavaVersion().classpath("junit").logCompilationWarningsAndErrors(true).build())
12+
}
13+
14+
@Test
15+
fun `one inner class`() = rewriteRun(java(
16+
"""
17+
import org.junit.Test;
18+
import org.junit.experimental.runners.Enclosed;
19+
import org.junit.runner.RunWith;
20+
21+
@RunWith(Enclosed.class)
22+
public class RootTest {
23+
public static class InnerTest {
24+
@Test
25+
public void test() {}
26+
}
27+
}
28+
""".trimIndent(), """
29+
import org.junit.Test;
30+
import org.junit.jupiter.api.Nested;
31+
32+
33+
34+
public class RootTest {
35+
@Nested
36+
public class InnerTest {
37+
@Test
38+
public void test() {}
39+
}
40+
}
41+
""".trimIndent()
42+
))
43+
44+
@Test
45+
fun `multiple inner classes`() = rewriteRun(java(
46+
"""
47+
import org.junit.Test;
48+
import org.junit.experimental.runners.Enclosed;
49+
import org.junit.runner.RunWith;
50+
51+
@RunWith(Enclosed.class)
52+
public class RootTest {
53+
public static class InnerTest {
54+
@Test
55+
public void test() {}
56+
}
57+
58+
public static class Inner2Test {
59+
@Test
60+
public void test() {}
61+
62+
public static class InnermostTest {
63+
@Test
64+
public void test() {}
65+
}
66+
}
67+
}
68+
""".trimIndent(), """
69+
import org.junit.Test;
70+
import org.junit.jupiter.api.Nested;
71+
72+
73+
74+
public class RootTest {
75+
@Nested
76+
public class InnerTest {
77+
@Test
78+
public void test() {}
79+
}
80+
81+
@Nested
82+
public class Inner2Test {
83+
@Test
84+
public void test() {}
85+
86+
@Nested
87+
public class InnermostTest {
88+
@Test
89+
public void test() {}
90+
}
91+
}
92+
}
93+
""".trimIndent()
94+
))
95+
96+
@Test
97+
fun `recognizes test annotation with arguments`() = rewriteRun(java(
98+
"""
99+
import org.junit.Test;
100+
import org.junit.experimental.runners.Enclosed;
101+
import org.junit.runner.RunWith;
102+
103+
@RunWith(Enclosed.class)
104+
public class RootTest {
105+
public static class InnerTest {
106+
@Test(timeout = 10)
107+
public void test() {}
108+
}
109+
}
110+
""".trimIndent(), """
111+
import org.junit.Test;
112+
import org.junit.jupiter.api.Nested;
113+
114+
115+
116+
public class RootTest {
117+
@Nested
118+
public class InnerTest {
119+
@Test(timeout = 10)
120+
public void test() {}
121+
}
122+
}
123+
""".trimIndent()
124+
))
125+
126+
@Test
127+
fun `does not annotate non-test inner class`() = rewriteRun(java(
128+
"""
129+
import org.junit.Test;
130+
import org.junit.experimental.runners.Enclosed;
131+
import org.junit.runner.RunWith;
132+
133+
@RunWith(Enclosed.class)
134+
public class RootTest {
135+
public static class InnerTest {
136+
@Test
137+
public void test() {}
138+
}
139+
140+
public static class Foo {
141+
public void bar() {}
142+
}
143+
}
144+
""".trimIndent(), """
145+
import org.junit.Test;
146+
import org.junit.jupiter.api.Nested;
147+
148+
149+
150+
public class RootTest {
151+
@Nested
152+
public class InnerTest {
153+
@Test
154+
public void test() {}
155+
}
156+
157+
public static class Foo {
158+
public void bar() {}
159+
}
160+
}
161+
""".trimIndent()
162+
))
163+
}

0 commit comments

Comments
 (0)