Skip to content

Commit dcf156e

Browse files
author
Tim te Beek
authored
Add missing @nested annotation (#257)
Fixes #215
1 parent b224699 commit dcf156e

File tree

3 files changed

+281
-0
lines changed

3 files changed

+281
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
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.internal.lang.Nullable;
25+
import org.openrewrite.java.JavaIsoVisitor;
26+
import org.openrewrite.java.JavaParser;
27+
import org.openrewrite.java.JavaTemplate;
28+
import org.openrewrite.java.JavaVisitor;
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+
import org.openrewrite.java.tree.TypeUtils;
34+
35+
import java.time.Duration;
36+
import java.util.*;
37+
38+
import static org.openrewrite.Parser.Input.fromString;
39+
40+
@Value
41+
@EqualsAndHashCode(callSuper = true)
42+
public class AddMissingNested extends Recipe {
43+
private static final String NESTED = "org.junit.jupiter.api.Nested";
44+
private static final List<String> TEST_ANNOTATIONS = Arrays.asList(
45+
"org.junit.jupiter.api.Test",
46+
"org.junit.jupiter.api.TestTemplate",
47+
"org.junit.jupiter.api.RepeatedTest",
48+
"org.junit.jupiter.params.ParameterizedTest",
49+
"org.junit.jupiter.api.TestFactory");
50+
51+
@Override
52+
public String getDisplayName() {
53+
return "JUnit5 inner test classes should be annotated with `@Nested`.";
54+
}
55+
56+
@Override
57+
public String getDescription() {
58+
return "Adds `@Nested` to inner classes that contain JUnit 5 tests.";
59+
}
60+
61+
@Override
62+
protected @Nullable TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
63+
return new JavaVisitor<ExecutionContext>() {
64+
@Override
65+
public J visitJavaSourceFile(JavaSourceFile cu, ExecutionContext executionContext) {
66+
TEST_ANNOTATIONS.forEach(ann -> doAfterVisit(new UsesType<>(ann)));
67+
return cu;
68+
}
69+
};
70+
}
71+
72+
@Override
73+
public Duration getEstimatedEffortPerOccurrence() {
74+
return Duration.ofMinutes(1);
75+
}
76+
77+
@Override
78+
public Set<String> getTags() {
79+
return Collections.singleton("RSPEC-5790");
80+
}
81+
82+
@Override
83+
public TreeVisitor<?, ExecutionContext> getVisitor() {
84+
return new JavaIsoVisitor<ExecutionContext>() {
85+
@Override
86+
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
87+
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
88+
cd = cd.withBody((J.Block) new AddNestedAnnotationVisitor().visit(cd.getBody(), ctx, getCursor()));
89+
maybeAddImport(NESTED);
90+
return cd;
91+
}
92+
};
93+
}
94+
95+
public static class AddNestedAnnotationVisitor extends JavaIsoVisitor<ExecutionContext> {
96+
@Override
97+
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
98+
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
99+
boolean alreadyNested = classDecl.getLeadingAnnotations().stream()
100+
.anyMatch(a -> TypeUtils.isOfClassType(a.getType(), NESTED));
101+
if (!alreadyNested && hasTestMethods(cd)) {
102+
cd = cd.withTemplate(getNestedJavaTemplate(), cd.getCoordinates().addAnnotation(Comparator.comparing(
103+
J.Annotation::getSimpleName)));
104+
cd.getModifiers().removeIf(modifier -> modifier.getType().equals(J.Modifier.Type.Static));
105+
}
106+
return cd;
107+
}
108+
109+
@NotNull
110+
private JavaTemplate getNestedJavaTemplate() {
111+
return JavaTemplate.builder(this::getCursor, "@Nested")
112+
.javaParser(() -> JavaParser.fromJavaVersion().dependsOn(Collections.singletonList(
113+
fromString("package org.junit.jupiter.api;\npublic @interface Nested {}"))).build())
114+
.imports(NESTED).build();
115+
}
116+
117+
private static boolean hasTestMethods(final J.ClassDeclaration cd) {
118+
return TEST_ANNOTATIONS.stream().anyMatch(ann -> !FindAnnotations.find(cd, "@" + ann).isEmpty());
119+
}
120+
}
121+
}

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

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

0 commit comments

Comments
 (0)