Skip to content

Commit

Permalink
ClassCanBeStatic: Exclude JUnit @Nested classes
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ljrmorgan committed Jan 2, 2023
1 parent 8eae200 commit c13015f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
tags = {StandardTags.STYLE, StandardTags.PERFORMANCE})
public class ClassCanBeStatic extends BugChecker implements ClassTreeMatcher {

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

Expand Down Expand Up @@ -77,6 +78,9 @@ public Description matchClass(ClassTree tree, VisitorState state) {
if (CanBeStaticAnalyzer.referencesOuter(tree, currentClass, state)) {
return NO_MATCH;
}
if (hasAnnotation(currentClass, JUNIT_NESTED_ANNOTATION, state)) {
return NO_MATCH;
}
if (tree.getMembers().stream().anyMatch(m -> hasAnnotation(m, REFASTER_ANNOTATION, state))) {
return NO_MATCH;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,4 +401,28 @@ public void refaster() {
"}")
.doTest();
}

@Test
public void junitNestedClass() {
compilationHelper
.addSourceLines(
"Nested.java",
"package org.junit.jupiter.api;",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.RetentionPolicy;",
"import java.lang.annotation.Target;",
"@Target(ElementType.TYPE)",
"@Retention(RetentionPolicy.RUNTIME)",
"public @interface Nested {}")
.addSourceLines(
"A.java",
"import org.junit.jupiter.api.Nested;",
"public class A {",
" @Nested class Inner {",
" void f() {}",
" }",
"}")
.doTest();
}
}

0 comments on commit c13015f

Please sign in to comment.