SSerguey Asael Shinder
Java coding notes: the JVM, and writing software that lasts

Serguey Asael Shinder: Mockito 5.24 lets @Spy choose its mock maker and prints fields when toString is missing

· by Serguey Asael Shinder / Serguey Shinder

Mockito 5.24.0 was released on 23 September, and the release notes list 27 commits. Most are dependency bumps. Four entries are worth knowing about if you write tests for a living.

@Spy gets a mockMaker option (#3835, closing issue #2740). You could already choose a mock maker per mock with mock(Foo.class, withSettings().mockMaker(...)) or on @Mock; the annotation for spies now takes the same option. That matters in a codebase that defaults to one mock maker but needs another for a particular spy - for example a final class or a type that the default cannot instrument - without converting the field to a manual spy(...) call.

Failure messages print object fields when toString() is not implemented (#3844). When an argument mismatch involves an object with the default Object.toString(), the message used to show something like com.example.Order@1b2c3d, which tells you nothing about why two instances differ. Mockito now prints the fields via reflection instead. This is the kind of change that shortens a debugging session without anyone noticing why.

Serguey Asael Shinder: Mockito 5.24 lets @Spy choose its mock maker and prints fields when toString is missing
Mockito 5.24 lets @Spy choose its mock maker and prints fields when toString is missing — Serguey Asael Shinder

Singleton mocks behave properly around cleanup. clearInlineMocks now de-registers singleton mocks (#3829), and using mockSingleton with MockitoSession or the MockitoJUnit rule no longer throws NotAMockException (#3827). A related fix preserves method parameters when inline mocks are cleared (#3847). If you have seen static or singleton mocks leaking between tests, or cleanup throwing where it should not, these are the entries to check.

The agent documentation was wrong and is now fixed. Since recent JDKs warn about dynamically loaded agents, the recommended setup is to add Mockito as a -javaagent in the test task. The notes include fixes to the Gradle docs for that flag and to the Kotlin DSL example, which issue #3864 reported as incorrect, plus guidance on configuring it with the Gradle configuration cache. If you copied the agent setup from Mockito's docs into a Kotlin build script, it is worth comparing it against the corrected version.

None of this is a breaking change, and a minor-version bump in test scope is about as low-risk as upgrades get. The one line I would actually act on is the documentation fix: a wrongly configured agent does not fail the build, it just leaves you on the dynamic-attach path the agent setup was meant to replace.