Fix NotAMockException when using mockSingleton with MockitoJUnit by jselbo · Pull Request #3827 · mockito/mockito · GitHub
Skip to content

Fix NotAMockException when using mockSingleton with MockitoJUnit - #3827

Merged
raphw merged 1 commit into
mockito:mainfrom
jselbo:singleton-fix
May 26, 2026
Merged

raphw merged 1 commit into
mockito:mainfrom
jselbo:singleton-fix

Conversation

@jselbo

@jselbo jselbo commented May 26, 2026

Copy link
Copy Markdown
Collaborator

Fixes #3826

The cause of this is that mockSingleton implementation overloaded the existing MockingProgress#mockingStarted callback. When using MockitoJUnit rule, UniversalTestListener uses this callback to track created mocks. If the scoped singleton mock is closed, then the testFinished downstream logic would look up mocking details on the singleton which is no longer a mock leading to this exception.

It was probably a mistake to reuse the mockingStarted callback originally - let's mimic the mockStatic path which uses its own dedicated callback for reporting created static mocks.

Note that the unused-stubbing detector stuff (used with "strict stubs" strictness) currently does not support static mocks, and it does not support singleton mocks either. That seems okay; a future PR can add support if desired.


Checklist

  • Read the contributing guide
  • PR should be motivated, i.e. what does it fix, why, and if relevant how
  • If possible / relevant include an example in the description, that could help all readers
    including project members to get a better picture of the change
  • Avoid other runtime dependencies
  • Meaningful commit history ; intention is important please rebase your commit history so that each
    commit is meaningful and help the people that will explore a change in 2 years
  • The pull request follows coding style (run ./gradlew spotlessApply for auto-formatting)
  • Mention Fixes #<issue number> in the description if relevant
  • At least one commit should end with Fixes #<issue number> if relevant

@codecov-commenter

Copy link
Copy Markdown

@raphw

raphw commented May 26, 2026

Copy link
Copy Markdown
Member

@raphw
raphw merged commit af081a3 into mockito:main May 26, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NotAMockException when using mockSingleton with MockitoSession or MockitoJUnit

3 participants