Skip to content

Keep early returns in TestMethodsShouldBeVoid and KotlinTestMethodsShouldReturnUnit - #1217

Merged
timtebeek merged 4 commits into
mainfrom
tim/test-methods-void-keep-early-returns
Oct 24, 2026
Merged

timtebeek merged 4 commits into
mainfrom
tim/test-methods-void-keep-early-returns

Conversation

@timtebeek

Copy link
Copy Markdown
Member

TestMethodsShouldBeVoid and KotlinTestMethodsShouldReturnUnit deleted every return in a test method. A guard such as if (System.getenv("SKIP") != null) { return 0; } then no longer exited, so the rest of the test ran and could fail. The recipes now only remove a return that is the last statement of the method (keeping a call like return calculate(); as calculate();), and turn every other return value; into return;:

@Test
void testMethod() {
    if (System.getenv("SKIP") != null) {
        return;
    }
    fail();
}

They leave a method unchanged when an early return's value has side effects, when it overrides another method, when it is called or referenced elsewhere in the same file (a test reused as a helper), when it has no body (previously an NPE on abstract test methods), or, in Kotlin, when a lambda returns from the test method. Returns in local classes and Kotlin local functions are no longer touched. TestMethodsShouldBeVoid also stops visiting Kotlin files, where it printed fun testMethod(): void { }.

Fixes item C4 of #1211.

The recipe also visited Kotlin files, where it replaced the `Int` return type with a Java `void` primitive and removed the `return` statements, printing `fun testMethod(): void { }`, which does not compile. Kotlin test methods are handled by `KotlinTestMethodsShouldReturnUnit`, so this recipe now only accepts Java compilation units.
…sShouldReturnUnit`

Both recipes deleted every `return` in a test method, so a guard like `if (skip) { return 0; }` stopped exiting and the rest of the test ran anyway. Only a `return` that is the last statement of the method is now removed (keeping its expression when it is a valid expression statement); any other `return` loses just its value. Methods are left unchanged when an early return's value has side effects, when a Kotlin lambda returns from the test method, when the method overrides another, is called or referenced elsewhere in the same file, or has no body (previously an NPE). Returns in local classes and Kotlin local functions are no longer touched.
@timtebeek
timtebeek merged commit 1786a40 into main Oct 24, 2026
2 checks passed
@timtebeek
timtebeek deleted the tim/test-methods-void-keep-early-returns branch October 24, 2026 12:11
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

1 participant