Skip to content

Commit c13015f

Browse files
committed
ClassCanBeStatic: Exclude JUnit @Nested classes
From the [JUnit docs](https://junit.org/junit5/docs/current/user-guide/#writing-tests-nested): > Only non-static nested classes (i.e. inner classes) can serve as `@Nested` test classes.
1 parent 8eae200 commit c13015f

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

core/src/main/java/com/google/errorprone/bugpatterns/ClassCanBeStatic.java

+4
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
tags = {StandardTags.STYLE, StandardTags.PERFORMANCE})
4444
public class ClassCanBeStatic extends BugChecker implements ClassTreeMatcher {
4545

46+
private static final String JUNIT_NESTED_ANNOTATION = "org.junit.jupiter.api.Nested";
4647
private static final String REFASTER_ANNOTATION =
4748
"com.google.errorprone.refaster.annotation.BeforeTemplate";
4849

@@ -77,6 +78,9 @@ public Description matchClass(ClassTree tree, VisitorState state) {
7778
if (CanBeStaticAnalyzer.referencesOuter(tree, currentClass, state)) {
7879
return NO_MATCH;
7980
}
81+
if (hasAnnotation(currentClass, JUNIT_NESTED_ANNOTATION, state)) {
82+
return NO_MATCH;
83+
}
8084
if (tree.getMembers().stream().anyMatch(m -> hasAnnotation(m, REFASTER_ANNOTATION, state))) {
8185
return NO_MATCH;
8286
}

core/src/test/java/com/google/errorprone/bugpatterns/ClassCanBeStaticTest.java

+24
Original file line numberDiff line numberDiff line change
@@ -401,4 +401,28 @@ public void refaster() {
401401
"}")
402402
.doTest();
403403
}
404+
405+
@Test
406+
public void junitNestedClass() {
407+
compilationHelper
408+
.addSourceLines(
409+
"Nested.java",
410+
"package org.junit.jupiter.api;",
411+
"import java.lang.annotation.ElementType;",
412+
"import java.lang.annotation.Retention;",
413+
"import java.lang.annotation.RetentionPolicy;",
414+
"import java.lang.annotation.Target;",
415+
"@Target(ElementType.TYPE)",
416+
"@Retention(RetentionPolicy.RUNTIME)",
417+
"public @interface Nested {}")
418+
.addSourceLines(
419+
"A.java",
420+
"import org.junit.jupiter.api.Nested;",
421+
"public class A {",
422+
" @Nested class Inner {",
423+
" void f() {}",
424+
" }",
425+
"}")
426+
.doTest();
427+
}
404428
}

0 commit comments

Comments
 (0)