skip to content

Mockito (Mocking)

Mockito in practice: creating mocks and spies, stubbing, verifying interactions, matching and capturing arguments, annotation-driven injection, and the static-mocking escape hatch. Interviewers expect both the API and a view on how much mocking is too much.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

page 2 of 2

What is the thread-local scope of a MockedStatic, and how does it affect concurrent or async code under test?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A MockedStatic only intercepts static calls made on the same thread that created it. Code under test that runs the static call on a different thread (a thread pool, an async task) sees the real method, not your stub.

open as a page

Explain how @InjectMocks resolves which mock goes where, and what happens when multiple mocks share the same type.

level: seniorimportance: should knowfreq 55%

basics

~20 s

Mockito tries constructor injection, then setters, then fields. It matches mocks by type; if several mocks have the same type it falls back to matching the field name. Anything it can't match is left null.

open as a page

How does Mockito.mock create a mock at the bytecode level, and what limits exist for final classes, final methods, and static methods?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Mockito generates the mock at runtime by subclassing the type (using ByteBuddy) and overriding its methods. The default subclass approach can't override final classes/methods or static methods. The newer inline mock maker (default in Mockito 5) can mock final and static via mockStatic.

open as a page

When should you mock a collaborator versus using the real object (or a fake), and what are the risks of over-mocking?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Mock collaborators that are slow, external, non-deterministic, or hard to set up (databases, HTTP, clocks). Use the real object for simple value or pure-logic dependencies. Over-mocking couples tests to implementation details and can hide real integration bugs.

open as a page

What is Mockito's constraint on stubbing checked exceptions, and why does it exist?

level: seniorimportance: should knowfreq 50%

basics

~10 s

You can only stub a checked exception that the method actually declares with throws. Unchecked exceptions (RuntimeException/Error) are always allowed. Otherwise Mockito fails with "Checked exception is invalid for this method!".

open as a page

When and how do you use thenAnswer (and the related thenReturn vs thenAnswer distinction) to produce dynamic mock responses based on the call's arguments?

level: seniorimportance: should knowfreq 45%

basics

~20 s

thenReturn gives a fixed value computed once. thenAnswer runs your code on every call, so you can build the return value from the actual arguments — useful when the answer depends on what was passed in.

open as a page

How does Mockito's InOrder verify the ordering of interactions, and across one or multiple mocks?

level: seniorimportance: should knowfreq 48%

basics

~10 s

InOrder lets you assert calls happened in a specific sequence. You create inOrder(mockA, mockB), then call inOrder.verify(...) in the order you expect; Mockito checks the calls occurred in that relative order.

open as a page

What is the difference between verifyNoInteractions and verifyNoMoreInteractions, and how do you use each correctly?

level: seniorimportance: should knowfreq 55%

basics

~10 s

verifyNoInteractions(mock) asserts the mock was never used at all. verifyNoMoreInteractions(mock) is called after your verify() calls and asserts there were no leftover, unverified interactions beyond those.

open as a page

When does heavy use of any() argument matchers weaken a test suite, and how do you decide between permissive matchers, eq()/argThat specificity, and ArgumentCaptor at scale?

level: principalimportance: should knowfreq 35%

basics

~20 s

Using any() for every argument makes tests pass even when the code passes wrong values, so bugs slip through. Match the arguments that carry the test's intent with eq()/argThat, relax only the truly irrelevant ones, and capture when you need detailed checks.

open as a page

Why is frequently needing to mock static methods often considered a design smell, and what refactorings remove the need?

level: principalimportance: should knowfreq 45%

basics

~20 s

Reaching for static mocks usually means your code calls hard-coded global things (clocks, randomness, static singletons) it can't swap out for tests. Injecting those as parameters or interfaces makes the code testable with plain mocks and removes the need.

open as a page

When would you avoid @InjectMocks in favour of constructing the system under test explicitly, and what does that say about your production code?

level: principalimportance: should knowfreq 40%

basics

~20 s

Avoid @InjectMocks when wiring is ambiguous or hidden — instead just call new Service(mock1, mock2). If you can't construct it cleanly, your production code probably relies on field injection or has too many dependencies, which is a design smell.

open as a page

When would you reach for a spy over a mock, and what design risks does heavy spy usage signal?

level: principalimportance: should knowfreq 45%

basics

~20 s

Use a mock by default to fully isolate a dependency. Reach for a spy only when you need most of an object's real behavior but want to override or verify a small part. Lots of spies usually means a class is hard to test and probably doing too much.

open as a page

What is strict stubbing in modern Mockito, and what problems (UnnecessaryStubbingException, PotentialStubbingProblem) does it surface that lenient stubbing hides?

level: principalimportance: should knowfreq 30%

basics

~20 s

Strict stubbing (the default now) flags stubs your test never used and warns when you call a stubbed method with arguments that don't match what you stubbed. It catches dead and mismatched stubs that the old lenient mode silently ignored.

open as a page

Show how BDDMockito makes a unit test read as Given-When-Then, and explain what belongs in each section.

level: middleimportance: nice to knowfreq 38%

basics

~10 s

Given = set up the mocks with given().willReturn(). When = call the method you're testing. Then = check results with assertions and then(mock).should() verifications. BDDMockito's method names match those three section labels.

open as a page

BDDMockito is pure aliasing. Given that, what guidance would you give a team about adopting it, and what subtle pitfalls should they watch for?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Pick one style per test (or per codebase) and stay consistent. Don't mix given() with verify() in the same test. Remember void stubbing flips order. Otherwise it behaves exactly like normal Mockito, so there are no new runtime risks.

open as a page

How do you make a mock throw on the first call but succeed on retries, and when would you reach for thenAnswer/doAnswer instead of thenThrow?

level: seniorimportance: nice to knowfreq 35%

basics

~10 s

Chain stubs: when(mock.call()).thenThrow(new TimeoutException()).thenReturn(value). The first call throws, later calls return. Use thenAnswer/doAnswer when whether (or what) to throw depends on the actual arguments.

open as a page

What are the common pitfalls and test-design trade-offs of using ArgumentCaptor?

level: principalimportance: nice to knowfreq 30%

basics

~20 s

Captors can record nothing if the call didn't happen, return the wrong value with multiple calls, fail with NPE if @Captor isn't initialized, and capture references (not snapshots) of mutable objects. Overusing them couples tests to internal details.

open as a page

showing 31–47 of 47