Skip to content

Reuse MockedStatic for consecutive stubbings of the same class#1005

Open
timtebeek wants to merge 2 commits into
mainfrom
tim/fix-issue-1004
Open

Reuse MockedStatic for consecutive stubbings of the same class#1005
timtebeek wants to merge 2 commits into
mainfrom
tim/fix-issue-1004

Conversation

@timtebeek
Copy link
Copy Markdown
Member

@timtebeek timtebeek commented May 22, 2026

Summary

  • MockitoWhenOnStaticToMockStatic previously created nested try (MockedStatic<X>) blocks for sibling Mockito.when() calls on the same static class. Mockito 5 rejects this at runtime with static mocking is already registered in the current thread.
  • Subsequent same-class stubbings (siblings at the same level, or nested inside if/loop/etc. inner blocks) now share the enclosing MockedStatic.

What changed

  • Thread a pendingResources map (FQN → variable name) through the recursive maybeWrapStatementsInTryWithResourcesMockedStatic so the second when(X.foo()) in the same block reuses the just-created mockX1 instead of opening a nested try.
  • Maintain a visitor-scoped generatedMocks (variable name → FQN) map as a fallback in getMatchingFilteredResources for nested blocks. Needed because JavaTemplate-generated try(MockedStatic<X> ...) resources end up with MockedStatic<{undefined}> as their declared type, breaking pure type-based lookup.
  • Fixed reuseMockedStatic to use the cursor's actual block for JavaTemplate.apply coordinates (the recursive caller was passing a synthetic block not in the cursor tree, causing the wrong statement to be returned) and to preserve the original statement's prefix (blank lines).

Test plan

  • New shouldShareSingleMockedStaticForConsecutiveStubbingsOfSameClass covers the exact case from MockitoWhenOnStaticToMockStatic creates nested MockedStatic blocks for the same class #1004.
  • Updated shouldHandleMultipleStaticMocksAndNestedStatements — its previous expected output codified the broken nested-try behavior; now expects a single mockA1 shared across siblings and inside the if-block.
  • All 37 existing tests in MockitoWhenOnStaticToMockStaticTest pass.

Fixes #1004: `MockitoWhenOnStaticToMockStatic` created nested
`try (MockedStatic<X>)` blocks for sibling `Mockito.when()` calls on
the same static class, which Mockito 5 rejects at runtime with
"static mocking is already registered in the current thread".

Subsequent same-class stubbings (siblings or nested in inner blocks)
now share the enclosing `MockedStatic`.
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.

MockitoWhenOnStaticToMockStatic creates nested MockedStatic blocks for the same class

1 participant