Repository navigation
Consolidate multiple @Before/@After methods when migrating to JUnit Jupiter - #1246
ApekshaAmbala wants to merge 7 commits into
Conversation
MBoegers
left a comment
There was a problem hiding this comment.
Tested exact PR head 597a1412d1afb4e7d949c7d04c4aef3e47e2ecca using the requested review-recipe-pr skill (https://github.com/moderneinc/rewrite-spring/blob/main/.claude/skills/review-recipe-pr/SKILL.md).
Requesting changes for five confirmed correctness issues below. The existing recipe test class has 12 passing tests and 1 pre-existing disabled test. Nine added edge-case probes produce 7 failures (5 distinct issues) and 2 passing controls. The probes use normal RewriteTest validation; compiler probes compile the actual transformed source, and behavior probes invoke its generated wrappers. Separate JUnit 4.13.2 runtime controls confirm the original ordering and cleanup behavior.
Compilation succeeds. Focused check also passes license and recipe CSV validation; its failure is the reproduced edge-case tests. Dependency downloads required a local Maven-mirror init script to avoid Maven Central HTTP 429 responses. No author-branch changes were pushed. The repository-wide suite was not run; these focused failures already demonstrate unsafe migration output.
| // Remove the annotations from original methods using RemoveAnnotationVisitor | ||
| // which properly handles spacing | ||
| for (J.MethodDeclaration targetMethod : targetMethods) { | ||
| doAfterVisit(new RemoveAnnotationVisitor(matcher)); |
There was a problem hiding this comment.
[P1] Limit annotation removal to the methods being consolidated
Could we remove the annotation only from targetMethods, rather than queueing a compilation-unit-wide RemoveAnnotationVisitor? targetMethod is unused in this loop, so consolidating one class also strips @Before from sibling and nested classes that have only one setup method. Those methods get neither @BeforeEach nor a wrapper and silently stop running.
Reproducer input (also reproduced with Single nested inside Multiple):
import org.junit.Before;
class Multiple {
@Before public void first() {}
@Before public void second() {}
}
class Single {
@Before public void only() {}
}A rewriteRun(java(input, spec -> spec.after(source -> { assertThat(source.substring(source.indexOf("class Single"))).contains("@BeforeEach"); return source; }))) test fails: the output is class Single { public void only() {} } with no lifecycle annotation. A separate-source-file control passes.
|
|
||
| JavaTemplate template = JavaTemplate.builder( | ||
| "@" + jupiterAnnotation + "\n" + | ||
| "void " + consolidatedMethodName + "() {\n" + |
There was a problem hiding this comment.
[P1] Propagate checked exceptions to the generated wrapper
Could we preserve the checked exceptions declared by the original lifecycle methods in the generated method's throws clause (or otherwise handle them)? Valid and common JUnit 4 fixtures become uncompilable because the new wrapper unconditionally declares void setUp() / void tearDown() without throws.
Reproducer:
import org.junit.Before;
public class Checked {
@Before public void first() throws java.io.IOException {}
@Before public void second() throws Exception {}
}I ran this through the recipe and compiled the generated source with JavaCompiler: first(); fails with "unreported exception IOException; must be caught or declared to be thrown", and second(); likewise fails for Exception. Please add a regression test for both setup and teardown exceptions.
|
|
||
| JavaTemplate template = JavaTemplate.builder( | ||
| "@" + jupiterAnnotation + "\n" + | ||
| "void " + consolidatedMethodName + "() {\n" + |
There was a problem hiding this comment.
[P1] Choose a wrapper name that is safe in the class hierarchy
Could we choose an unused wrapper name, checking existing and inherited methods? setUp and tearDown are especially common fixture names. The recipe currently creates a duplicate method, and can also introduce an invalid override of an inherited final method.
Reproducer:
import org.junit.Before;
public class Collision {
@Before public void setUp() {}
@Before public void second() {}
}Compiling the actual transformed output fails with "method setUp() is already defined in class Collision". The wrapper also contains a setUp(); self-call. A second compiler probe with class Parent { public final void setUp() {} } and a child containing @Before first() / @Before second() fails because the generated method overrides a final method. The same naming issue applies to tearDown.
|
|
||
| // Create consolidated method | ||
| String methodBody = targetMethods.stream() | ||
| .map(m -> m.getSimpleName() + "();") |
There was a problem hiding this comment.
[P1] Continue running cleanup methods when an earlier cleanup throws
Could we preserve the lifecycle engine's exception handling when consolidating @After methods? These straight-line calls stop at the first exception. JUnit 4 runs the remaining cleanup methods even when an earlier cleanup fails, so this can leak resources and contaminate later tests.
Reproducer:
import org.junit.After;
public class Cleanup {
public boolean released;
@After public void first() { throw new IllegalStateException("failure"); }
@After public void second() { released = true; }
}The regression probe transforms and compiles this source, invokes the generated tearDown(), catches its exception, then asserts released is true. It fails (released == false). I also ran an equivalent fixture with a @Test through JUnitCore 4.13.2: the first failure is reported and the second cleanup does execute. A wrapper needs to preserve that behavior and report failures rather than simply calling each method in sequence.
| } | ||
|
|
||
| // Create consolidated method | ||
| String methodBody = targetMethods.stream() |
There was a problem hiding this comment.
[P1] Do not replace working JUnit 4 execution order with declaration order
Could we revisit the ordering policy before applying this consolidation automatically? Declaration order does not preserve the order JUnit 4 actually uses. JUnit 4.13.2 sorts reflected methods using its MethodSorter and builds the @Before list in reverse; it is not generally alphabetical or source order. This change can therefore break the same order-dependent fixtures it aims to repair.
Reproducer:
import org.junit.Before;
public class Order {
boolean ready;
@Before public void a() {
if (!ready) throw new IllegalStateException("z must run first");
}
@Before public void z() { ready = true; }
@org.junit.Test public void test() {}
}Verified with JUnitCore.runClasses(Order.class) on 4.13.2: this passes (z() executes before a()). The recipe generates setUp() { a(); z(); }; compiling and invoking that actual generated wrapper throws "z must run first". Please preserve the source runner's ordering where it is known, or use a conservative/manual migration for cases where it cannot be determined. Reference: https://junit.org/junit4/xref/org/junit/internal/MethodSorter.html .
MBoegers
left a comment
There was a problem hiding this comment.
Pushed regression coverage and review polish to 95b1dca2, including a merge of current main. For any next PRs:
- Keep regression tests with the recipe's test class, use versioned parser resources, and assert intended output. I added 14 edge-case cases, covering both setup and teardown where applicable, without relaxing RewriteTest validation or disabling failures.
- Compile actual transformed sources for compilation-sensitive changes, and execute their lifecycle methods for behavioral checks. The helper uses real Jupiter annotations,
@TempDir, and a closed classloader. A full-output Kotlin expectation exposed invalid Kotlin that the initial loose probe missed; this is a sixth correctness finding. - Apply the reviewed best-practices recipe output to the PR files. The implementation cleanup removes an unused import and simplifies stream operations. I also ran license formatting and regenerated the recipe CSV, retaining only this recipe's description and excluding unrelated dependency drift. I rejected one automated cleanup hunk because it would remove a still-used test variable.
Validation on the pushed head: compilation succeeds; license and recipe CSV checks pass. Focused tests have 13 passing, 13 failing, and 1 pre-existing skipped test. The 13 failures are active regression tests for the six reported correctness issues. The original 12 enabled tests still pass. These commits add tests and mechanical polish; behavioral corrections remain outstanding, and the PR is still not ready to approve. The full repository suite was not run.
| public Tree preVisit(Tree tree, ExecutionContext ctx) { | ||
| stopAfterPreVisit(); | ||
| // First do Java-specific consolidation | ||
| doAfterVisit(new JavaConsolidationVisitor(acc)); |
There was a problem hiding this comment.
[P1] Keep Java consolidation from producing invalid Kotlin
Could we limit this Java-template consolidation to Java compilation units (while retaining annotation migration for Kotlin), or build a proper Kotlin implementation? JavaIsoVisitor also adapts to Kotlin, so this visitor is not Java-only despite the comment.
The new ConsolidationEdgeCases#migrateMultipleKotlinLifecycleAnnotations test uses:
import org.junit.Before
class KotlinFixture {
@Before fun first() {}
@Before fun second() {}
}The actual transformed output contains invalid Kotlin:
@BeforeEach setUp():
void {
first()
second()
}The method annotations are also stripped from the original functions. The regression test expects valid annotation migration and fails against the pushed head. My first loose probe checked only that the literal Java string void setUp was absent, which missed this malformed rendering; the complete output assertion now catches it.
|
Fixed the six reported correctness issues in
Validation on this head: compilation succeeds; the lifecycle, JUnit migration, and ordering suites have 70 passing tests, 0 failures, and 1 pre-existing skipped test. License formatting and generated recipe CSV validation pass. The best-practices recipe was run and its relevant output reviewed; invalid cleanups that would remove used test variables were rejected. All original failing regression tests remain active. No co-author trailers or AI attribution were added. The full repository suite was not run. GitHub's |
Add setup and teardown coverage for checked exceptions, method name collisions, inherited final methods, and annotations in sibling and nested classes. Compile actual generated sources against Jupiter and execute generated lifecycle methods to cover cleanup failures and JUnit 4 ordering. Keep the known failures active, including invalid Kotlin output, so the review findings remain reproducible until the implementation is corrected.
Limit annotation removal to the consolidated declarations, choose wrapper names that avoid existing and generated inherited methods, and propagate checked exceptions. Preserve JUnit 4 method ordering and execute every cleanup, aggregating multiple failures with MultipleFailuresError. Keep Kotlin, overridden lifecycle methods, and unsupported ordering on the annotation migration path, and migrate ordering annotations after consolidation in the composite.
Consolidate multiple @Before/@after methods during JUnit migration
Extends
UpdateBeforeAfterAnnotationsto automatically consolidate multiple JUnit 4 lifecycle methods when migrating to JUnit Jupiter.Problem
JUnit 4 allows multiple
@Beforeand@Aftermethods in a class. While their execution order is implementation-defined, code often depends on declaration order. JUnit 5's documentation explicitly states that execution order for multiple lifecycle methods is "arbitrary", which can break tests that relied on a specific sequence.Solution
Convert
UpdateBeforeAfterAnnotationsfrom a simpleRecipeto aScanningRecipethat:@Beforeor@AftermethodssetUp()/tearDown()methods that preserve declaration orderChanges
UpdateBeforeAfterAnnotationsfromRecipetoScanningRecipe<Accumulator>ScanForMultipleLifecycleMethodsvisitor to detect consolidation candidatesJavaConsolidationVisitorto create consolidated lifecycle methods@Valueinstead of explicit@Getterannotations (Lombok best practice)Example
Before:
After:
Testing
Comprehensive test coverage includes:
Fixes