diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/NonFinalStaticField.java b/core/src/main/java/com/google/errorprone/bugpatterns/NonFinalStaticField.java index 78622b104d0..be7431db9b2 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/NonFinalStaticField.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/NonFinalStaticField.java @@ -55,6 +55,8 @@ public final class NonFinalStaticField extends BugChecker implements VariableTreeMatcher { private static final ImmutableSet ANNOTATIONS_TO_AVOID = ImmutableSet.of("Captor", "Inject", "Mock", "TestParameter"); + public static final ImmutableSet BEFORE_ALL_METHOD_ANNOTATIONS = + ImmutableSet.of("org.junit.BeforeClass", "org.junit.jupiter.api.BeforeAll"); @Override public Description matchVariable(VariableTree tree, VisitorState state) { @@ -185,7 +187,9 @@ private boolean isMutating(Kind kind) { public Void visitMethod(MethodTree tree, Void unused) { boolean prev = inBeforeMethod; try { - inBeforeMethod |= ASTHelpers.hasAnnotation(tree, "org.junit.BeforeClass", state); + inBeforeMethod |= + BEFORE_ALL_METHOD_ANNOTATIONS.stream() + .anyMatch(annotation -> ASTHelpers.hasAnnotation(tree, annotation, state)); return super.visitMethod(tree, null); } finally { inBeforeMethod = prev; diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/NonFinalStaticFieldTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/NonFinalStaticFieldTest.java index 6e350f629a6..ef1675eeaf7 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/NonFinalStaticFieldTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/NonFinalStaticFieldTest.java @@ -227,4 +227,35 @@ public void beforeClass() { "}") .doTest(); } + + @Test + public void beforeAll() { + compilationTestHelper + .addSourceLines( + "org/junit/jupiter/api/BeforeAll.java", + "package org.junit.jupiter.api;", + "", + "import java.lang.annotation.Documented;", + "import java.lang.annotation.ElementType;", + "import java.lang.annotation.Retention;", + "import java.lang.annotation.RetentionPolicy;", + "import java.lang.annotation.Target;", + "", + "@Target({ ElementType.ANNOTATION_TYPE, ElementType.METHOD })", + "@Retention(RetentionPolicy.RUNTIME)", + "@Documented", + "public @interface BeforeAll {", + "}") + .addSourceLines( + "Test.java", // + "import org.junit.jupiter.api.BeforeAll;", + "public class Test {", + " private static String foo;", + " @BeforeAll", + " public static void setup() {", + " foo = \"\";", + " }", + "}") + .doTest(); + } }