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

Analogous to #4215.

Resolves #4239.

Fixes #4251

FUTURE_COPYBARA_INTEGRATE_REVIEW=#4251 from DataDog:halil.sener/4239-non-final-static-field-junit-5-before-all 8a109a8
PiperOrigin-RevId: 597978105
  • Loading branch information
hisener authored and Error Prone Team committed Jan 22, 2024
1 parent 2cbed19 commit 812dc0a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ public final class NonFinalStaticField extends BugChecker implements VariableTre
private static final ImmutableSet<String> ANNOTATIONS_TO_AVOID =
ImmutableSet.of("Captor", "Inject", "Mock", "TestParameter");

private 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) {
var symbol = getSymbol(tree);
Expand Down Expand Up @@ -185,7 +188,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 812dc0a

Please sign in to comment.