Skip to content

Consolidate multiple @Before/@After methods when migrating to JUnit Jupiter - #1246

Open
ApekshaAmbala wants to merge 7 commits into
openrewrite:mainfrom
ApekshaAmbala:main
Open

ApekshaAmbala wants to merge 7 commits into
openrewrite:mainfrom
ApekshaAmbala:main

Conversation

@ApekshaAmbala

@ApekshaAmbala ApekshaAmbala commented Oct 26, 2026 •

Copy link
Copy Markdown

Consolidate multiple @Before/@after methods during JUnit migration

Extends UpdateBeforeAfterAnnotations to automatically consolidate multiple JUnit 4 lifecycle methods when migrating to JUnit Jupiter.

Problem

JUnit 4 allows multiple @Before and @After methods 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 UpdateBeforeAfterAnnotations from a simple Recipe to a ScanningRecipe that:

  1. Scans for classes with multiple @Before or @After methods
  2. Consolidates them into single setUp()/tearDown() methods that preserve declaration order
  3. Migrates annotations from JUnit 4 to Jupiter equivalents

Changes

  • Convert UpdateBeforeAfterAnnotations from Recipe to ScanningRecipe<Accumulator>
  • Add ScanForMultipleLifecycleMethods visitor to detect consolidation candidates
  • Add JavaConsolidationVisitor to create consolidated lifecycle methods
  • Replace double-brace initialization with helper method (anti-pattern cleanup)
  • Use @Value instead of explicit @Getter annotations (Lombok best practice)
  • Add comprehensive test coverage for consolidation scenarios

Example

Before:

class MyTest {
    @Before
    public void initDatabase() { /* ... */ }
    
    @Before  
    public void loadTestData() { /* ... */ }
}

After:

class MyTest {
    @BeforeEach
    void setUp() {
        initDatabase();
        loadTestData();
    }
    
    void initDatabase() { /* ... */ }
    
    void loadTestData() { /* ... */ }
}

Testing

Comprehensive test coverage includes:

  • Single method (no consolidation needed)
  • Multiple Before methods consolidation
  • Multiple After methods consolidation
  • Mixed scenarios (both Before and After)
  • Annotation migration correctness

Fixes

@MBoegers MBoegers left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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" +

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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" +

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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() + "();")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 MBoegers left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed regression coverage and review polish to 95b1dca2, including a merge of current main. For any next PRs:

  1. 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.
  2. 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.
  3. 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));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@MBoegers

Copy link
Copy Markdown
Collaborator

Fixed the six reported correctness issues in db5cd744, with generated metadata refreshed in 6675c615.

  1. Remove lifecycle annotations only from the consolidated method declarations, preserving sibling, nested, and local class fixtures. Keep Java templates out of Kotlin, and remove redundant old annotations before consolidation.
  2. Choose names that avoid existing and inherited methods, including wrappers generated for ancestors. A small scan skips consolidation where per-method overrides would otherwise execute a fixture twice. Checked exceptions propagate through wrappers.
  3. Preserve JUnit 4's deterministic lifecycle ordering. JVM-dependent and unsupported inherited ordering retain annotation migration only. The composite now consolidates before UseTestMethodOrder replaces the original ordering annotation; a full-composite regression test covers this sequence.
  4. Always execute remaining cleanups. Rethrow a single failure unchanged and aggregate multiple failures using MultipleFailuresError, including repeated exceptions and test-abort exceptions.

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 cgp check currently reports ACTION_REQUIRED, so local success does not establish final CI success. The original six findings are addressed; approval remains for a person after CI on the final head.

ApekshaAmbala and others added 7 commits November 19, 2026 00:00
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

JUnit 4 to 5 Migration: Tests with Multiple @Before Methods Fail Due to Arbitrary Execution Order

2 participants