Skip to content

Convert assertThrows with an Executable variable#1046

Merged
timtebeek merged 2 commits into
mainfrom
tim/assert-throws-variable-executable
Jun 20, 2026
Merged

Convert assertThrows with an Executable variable#1046
timtebeek merged 2 commits into
mainfrom
tim/assert-throws-variable-executable

Conversation

@timtebeek

@timtebeek timtebeek commented Jun 20, 2026

Copy link
Copy Markdown
Member

Problem

JUnitAssertThrowsToAssertExceptionType was already rewriting assertThrows(..., executable) into assertThatExceptionOfType(...).isThrownBy(executable) even when executable is a variable, but the result did not compile: the variable stayed typed as JUnit's org.junit.jupiter.api.function.Executable, while AssertJ's isThrownBy requires ThrowableAssert.ThrowingCallable. These are distinct functional interfaces — a lambda/method reference coerces to either, a typed variable does not.

Change

When the executable argument is a variable typed exactly as Executable, the recipe now also retypes its declaration (and references) to ThrowingCallable, adding/removing imports accordingly.

This is guarded: the conversion only proceeds when every usage of that variable is an assertThrows executable argument (or the variable's own declaration/assignment). If the same variable is also passed somewhere that requires an Executable (e.g. assertAll), the types can't both be satisfied, so the call is left untouched rather than emitting non-compiling code.

Tests

  • variableExecutable — local variable (the issue's core case)
  • variableExecutableWithMessage — 3-arg form with .as(...)
  • fieldExecutable — field declaration
  • doNotRetypeExecutableSharedWithOtherJUnitAssertion — guard: variable shared with assertAll is left unchanged

@timtebeek timtebeek merged commit 9321cbc into main Jun 20, 2026
1 check passed
@timtebeek timtebeek deleted the tim/assert-throws-variable-executable branch June 20, 2026 16:38
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Jun 20, 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.

JUnitAssertThrowsToAssertExceptionType does not convert cases where executable is a variable

1 participant