Skip to content

Commit

Permalink
ClassCanBeStatic: Exclude JUnit @Nested classes
Browse files Browse the repository at this point in the history
Exclude inner classes annotated with JUnit's `@Nested` annotation from the `ClassCanBeStatic` check. JUnit requires them to not be `static`.

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.

Fixes #956.

Fixes #3654

FUTURE_COPYBARA_INTEGRATE_REVIEW=#3654 from ljrmorgan:junit_nested_test_classes_cannot_be_static 3a5bd67
PiperOrigin-RevId: 503544057
  • Loading branch information
java-team-github-bot authored and Error Prone Team committed Jan 23, 2023
1 parent 1b8bf17 commit 7f8fde1
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -1041,7 +1041,8 @@ public static boolean shouldKeep(Tree tree) {
* though they are.
*/
private static final ImmutableSet<String> ANNOTATIONS_CONSIDERED_KEEP =
ImmutableSet.of("org.apache.beam.sdk.transforms.DoFn.ProcessElement");
ImmutableSet.of(
"org.apache.beam.sdk.transforms.DoFn.ProcessElement", "org.junit.jupiter.api.Nested");

private static final String USED_REFLECTIVELY = "UsedReflectively";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ public Description matchClass(ClassTree tree, VisitorState state) {
if (CanBeStaticAnalyzer.referencesOuter(tree, currentClass, state)) {
return NO_MATCH;
}
if (ASTHelpers.shouldKeep(tree)) {
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 7f8fde1

Please sign in to comment.