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 pageshowhide
explore
- Mockito Mock Creation5 questions
- Stubbing (when/thenReturn)5 questions
- Stubbing Exceptions (thenThrow)4 questions
- Verification (verify)5 questions
- Argument Matchers5 questions
- ArgumentCaptor5 questions
- Spy vs Mock4 questions
- @Mock / @InjectMocks5 questions
- Mocking Static Methods5 questions
- BDDMockito (given/willReturn)4 questions
questions
page 2 of 2What is the thread-local scope of a MockedStatic, and how does it affect concurrent or async code under test?
basics
~20 sA 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.
Explain how @InjectMocks resolves which mock goes where, and what happens when multiple mocks share the same type.
basics
~20 sMockito 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.
How does Mockito.mock create a mock at the bytecode level, and what limits exist for final classes, final methods, and static methods?
basics
~20 sMockito 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.
When should you mock a collaborator versus using the real object (or a fake), and what are the risks of over-mocking?
basics
~20 sMock 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.
What is Mockito's constraint on stubbing checked exceptions, and why does it exist?
basics
~10 sYou 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!".
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?
basics
~20 sthenReturn 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.
How does Mockito's InOrder verify the ordering of interactions, and across one or multiple mocks?
basics
~10 sInOrder 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.
What is the difference between verifyNoInteractions and verifyNoMoreInteractions, and how do you use each correctly?
basics
~10 sverifyNoInteractions(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.
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?
basics
~20 sUsing 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.
Why is frequently needing to mock static methods often considered a design smell, and what refactorings remove the need?
basics
~20 sReaching 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.
When would you avoid @InjectMocks in favour of constructing the system under test explicitly, and what does that say about your production code?
basics
~20 sAvoid @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.
When would you reach for a spy over a mock, and what design risks does heavy spy usage signal?
basics
~20 sUse 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.
What is strict stubbing in modern Mockito, and what problems (UnnecessaryStubbingException, PotentialStubbingProblem) does it surface that lenient stubbing hides?
basics
~20 sStrict 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.
Show how BDDMockito makes a unit test read as Given-When-Then, and explain what belongs in each section.
basics
~10 sGiven = 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.
BDDMockito is pure aliasing. Given that, what guidance would you give a team about adopting it, and what subtle pitfalls should they watch for?
basics
~20 sPick 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.
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?
basics
~10 sChain 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.
What are the common pitfalls and test-design trade-offs of using ArgumentCaptor?
basics
~20 sCaptors 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.
showing 31–47 of 47