Skip to content

Commit

Permalink
Do not report NonFinalStaticField findings for fields modified in `…
Browse files Browse the repository at this point in the history
…@BeforeAll` methods

Resolves #4239.
  • Loading branch information
hisener committed Jan 11, 2024
1 parent 43e3bd1 commit c0ce50c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
public final class NonFinalStaticField extends BugChecker implements VariableTreeMatcher {
private static final ImmutableSet<String> ANNOTATIONS_TO_AVOID =
ImmutableSet.of("Captor", "Inject", "Mock", "TestParameter");
public static final ImmutableSet<String> BEFORE_ALL_METHOD_ANNOTATIONS =
ImmutableSet.of("org.junit.BeforeClass", "org.junit.jupiter.api.BeforeAll");

@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

0 comments on commit c0ce50c

Please sign in to comment.