Skip to content

RemoveInitMocksIfRunnersSpecified: handle openMocks(this) as a try-with-resources resource - #1118

Draft
kmccarp wants to merge 1 commit into
mainfrom
fix-open-mocks-try-with-resources
Draft

RemoveInitMocksIfRunnersSpecified: handle openMocks(this) as a try-with-resources resource#1118
kmccarp wants to merge 1 commit into
mainfrom
fix-open-mocks-try-with-resources

Conversation

@kmccarp

@kmccarp kmccarp commented Sep 8, 2026

Copy link
Copy Markdown
Contributor
  • Fixes moderneinc/customer-requests#2533

Background / problem

RemoveInitMocksIfRunnersSpecified removes MockitoAnnotations.initMocks(this) and openMocks(this) once a test class is on @ExtendWith(MockitoExtension.class) or @RunWith(MockitoJUnitRunner.class). It only understood the call as a statement or as the right-hand side of an assignment. A user's test suite wrote it as a try-with-resources variable, try (AutoCloseable mocks = MockitoAnnotations.openMocks(this)) { ... }, and the recipe stripped the initializer, leaving try (AutoCloseable mocks;) {, which does not compile. Every affected test had to be fixed by hand.

Solution

The recipe now removes the resource itself and, when the try has nothing left, replaces it with its body so the test reads as if the call had never been there. It keeps the body as a plain block when inlining it would change meaning, and it leaves the try untouched in the few cases where there is no safe rewrite, so the output always compiles.

Test plan

  • New tests in RemoveInitMocksIfRunnersSpecifiedTest for the reported input, a second resource alongside it, and the cases where the recipe must fall back or leave the code alone
  • The two symptom tests fail on main and pass with the change
  • org.openrewrite.java.testing.mockito.* and org.openrewrite.java.testing.junit5.* pass

…th-resources resource

The recipe dropped the initializer of a try-with-resources variable when
it was MockitoAnnotations.openMocks(this) or initMocks(this), leaving
'try (AutoCloseable mocks;)' which does not compile. Remove the resource
instead, and unwrap the try into its body when nothing else remains.
Keep a plain block when inlining would collide with a later local or
lose comments, leave a try alone when its variable is still referenced
in the body or when the try is not directly inside a block, and never
drop a call that is a variable initializer.
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.

1 participant