Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,26 @@ public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations m
}
return anno;
}));
varDecls = removeFinalModifier(varDecls);
getCursor().dropParentUntil(J.ClassDeclaration.class::isInstance).putMessage("has-testName-rule", varDecls);
}
return varDecls;
}

private static J.VariableDeclarations removeFinalModifier(J.VariableDeclarations varDecls) {
List<J.Modifier> modifiers = varDecls.getModifiers();
List<J.Modifier> retained = ListUtils.filter(modifiers, mod -> mod.getType() != J.Modifier.Type.Final);
if (retained == modifiers) {
return varDecls;
}
Space prefix = modifiers.get(0).getPrefix();
if (retained.isEmpty()) {
return varDecls.withModifiers(retained).withTypeExpression(
varDecls.getTypeExpression() == null ? null : varDecls.getTypeExpression().withPrefix(prefix));
}
return varDecls.withModifiers(ListUtils.mapFirst(retained, mod -> mod.withPrefix(prefix)));
}

@Override
public J.@Nullable NewClass visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
J.NewClass nc = super.visitNewClass(newClass, ctx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,48 @@ private static class SomeInnerClass {
)
);
}

@Test
void ruleIsFinal() {
//language=java
rewriteRun(
java(
"""
import org.junit.Rule;
import org.junit.rules.TestName;

public class SomeTest {
@Rule
public final TestName name = new TestName();
protected String randomName() {
return name.getMethodName();
}
}
""",
"""
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInfo;

import java.lang.reflect.Method;
import java.util.Optional;

public class SomeTest {
\s
public String name;
protected String randomName() {
return name;
}

@BeforeEach
public void setup(TestInfo testInfo) {
Optional<Method> testMethod = testInfo.getTestMethod();
if (testMethod.isPresent()) {
this.name = testMethod.get().getName();
}
}
}
"""
)
);
}
}
Loading