Skip to content

Retain doNothing() for spies and partial mocks - #1101

Merged
timtebeek merged 4 commits into
mainfrom
tim/retain-donothing-for-partial-mocks
Aug 20, 2026
Merged

Retain doNothing() for spies and partial mocks#1101
timtebeek merged 4 commits into
mainfrom
tim/retain-donothing-for-partial-mocks

Conversation

@timtebeek

@timtebeek timtebeek commented Aug 20, 2026

Copy link
Copy Markdown
Member

Three cases are now retained:

  • @Mock(answer = Answers.CALLS_REAL_METHODS) — a partial mock, both qualified and statically imported
  • a @Mock field reassigned from Mockito.spy(..) before the stubbing runs
  • a local variable or parameter holding a spy that shadows a @Mock field

Other answers (RETURNS_DEEP_STUBS and friends) still do nothing for void methods, so those stubbings are still removed; there's a test pinning that.

`RemoveDoNothingForDefaultMocks` treated every `@Mock` field as a plain
mock, but a mock can still run real code for void methods:

- `@Mock(answer = Answers.CALLS_REAL_METHODS)` is a partial mock
- a `@Mock` field can be reassigned to `Mockito.spy(..)` before stubbing
- a local variable holding a spy can shadow a `@Mock` field

In each case removing the stubbing lets the real method execute.

Fixes #1099
Only a bare identifier was matched on the left-hand side, so a spy
assigned through `this` slipped past and the stubbing was still removed.
Variable identity is name plus owner, so a field and a local shadowing it
are told apart without the explicit owner check, and `this.mock` resolves
to the same variable as `mock`.
@timtebeek
timtebeek merged commit adcd588 into main Aug 20, 2026
1 check passed
@timtebeek
timtebeek deleted the tim/retain-donothing-for-partial-mocks branch August 20, 2026 12:00
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Aug 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

org.openrewrite.java.testing.mockito.MockitoBestPractices Unnecessary operations

1 participant