Mockito
The standard JVM mocking library: creating mocks and spies, stubbing behavior, capturing arguments, and verifying interactions. Interviewers ask because how much you mock says a lot about how you design and isolate units.
on this pageshowhide
explore
- Mocks, Spies & Injection19 questions
- Creating Mocks5 questions
- Spies & Partial Mocks5 questions
- @InjectMocks & Injection Rules5 questions
- Annotation Initialization4 questions
- Stubbing23 questions
- when / thenReturn / thenThrow5 questions
- Dynamic Answers (thenAnswer)4 questions
- doReturn / doThrow / doAnswer5 questions
- Consecutive & Void Stubbing5 questions
- BDDMockito Style4 questions
- Matchers & Captors16 questions
- Built-in Matchers4 questions
- Custom Matchers (argThat)4 questions
- The All-or-None Rule4 questions
- ArgumentCaptor4 questions
- Verification17 questions
- Verification Modes4 questions
- InOrder Verification5 questions
- Verifying Nothing Happened3 questions
- Async Verification (timeout)5 questions
- Advanced Mocking23 questions
- Static Mocking (mockStatic)4 questions
- Constructor Mocking (mockConstruction)4 questions
- Final Types & the Inline Mock Maker5 questions
- Deep Stubs4 questions
- Custom Default Answers6 questions
- Strictness & Mocking Hygiene16 questions
- Strictness Levels5 questions
- Strict-Stubbing Failures3 questions
- What to Mock4 questions
- Mocks vs Stubs vs Fakes (Vocabulary)4 questions
questions
114 · 6 sectionsYou create a Mockito mock of a Java interface and then call a method on it that you never stubbed. What does that call return, and what else happens?
basics
~20 sNo real code runs. Mockito returns the type's default value: null for objects, 0 for numbers, false for boolean, and an empty collection, Optional or stream for those types. Void methods do nothing. The call is recorded so you can verify it later.
A test class declares fields annotated with Mockito's @Mock, and the test fails with NullPointerException the first time one of those fields is used. Why are they null, and what are the ways to make them non-null?
basics
~20 s@Mock is only metadata; something must scan the test instance and assign the mocks. Enable one initializer: @ExtendWith(MockitoExtension.class) on JUnit 5, MockitoAnnotations.openMocks(this) in a setup method, or the JUnit 4 MockitoJUnitRunner/MockitoRule. Without one, the fields stay null.
In Mockito, what does the @InjectMocks annotation do to the field it is placed on, and where does it get the values it injects?
basics
~20 s@InjectMocks makes Mockito create a real instance of that field's type and push the test class's @Mock and @Spy fields into it as dependencies. The field under test is a real object, not a mock — only its collaborators are mocks.
In Mockito, what does Mockito.spy(new ArrayList<String>()) give you that Mockito.mock(ArrayList.class) does not — specifically, what happens when you call a method you never stubbed?
basics
~20 sOn a mock, an unstubbed method does nothing and returns a default — null, 0, false, or an empty collection. On a spy, an unstubbed method runs the real implementation. Both record calls, so both can be verified.
Compare registering Mockito's JUnit 5 extension with calling MockitoAnnotations.openMocks(this) in a setup method: what does the extension give you that the manual call does not, and when would you still choose the manual call?
basics
~20 sBoth create the annotated mocks per test. The extension additionally applies strict stubs (failing on unused or mismatched stubbings), validates Mockito usage after each test, closes the session for you, and can inject mocks as test-method parameters. openMocks does none of that but works in any framework and needs no extra artifact.
In Mockito, how do you make a stubbed method return a different value on each successive call, and what does the mock return once the test calls that method more times than you stubbed for?
basics
~20 sChain the answers: when(m.next()).thenReturn(1).thenReturn(2), or use the varargs shorthand thenReturn(1, 2). Calls consume answers in order. Once they run out, the mock keeps repeating the last answer forever — it does not reset, return null, or fail.
A teammate tries to stub a method whose return type is void by writing when(service.delete(id)).thenThrow(new IllegalStateException()) in a Mockito test, and it will not compile. Explain why, and show the form that does work.
basics
~10 swhen(...) takes a value as its argument, and a void call produces no value, so the expression is not legal Java. Use the do-family instead: doThrow(new IllegalStateException()).when(service).delete(id) — behaviour first, stubbed call last.
In a Mockito test you need a mock's return value to depend on the arguments of the call - for example a repository mock whose save() gives back whatever entity was passed in. How do you configure that stub, and how does it differ from stubbing a fixed value?
basics
~10 sUse thenAnswer instead of thenReturn: when(repo.save(any())).thenAnswer(inv -> inv.getArgument(0)). The lambda is an Answer that Mockito runs on every matching call, so the result is computed per call from the real arguments.
Explain how you tell a Mockito mock to return a specific value for a given method call, and what such a mock returns for methods you never stubbed.
basics
~10 sWrite when(mock.method(args)).thenReturn(value), or thenThrow(exception) for a failure path. Anything you do not stub returns the type's default: null for objects, 0 for numbers, false for boolean, and an empty collection for collection-returning methods.
A mailer collaborator's send(...) method has return type void. Using Mockito, how do you stub it so the first invocation throws an IOException and every later invocation succeeds silently?
basics
~10 sUse the do-family with a chain: doThrow(new IOException()).doNothing().when(mailer).send(any()). First call throws, later calls do nothing, because the last entry in the chain repeats. IOException must be declared by send(...) or Mockito rejects the stub.
When writing Mockito stubs and verifications, when should you wrap a plain value in ArgumentMatchers.eq(), and when is passing the raw value directly the better style?
basics
~20 sUse eq() only when the same call already uses another matcher, because matchers and raw values cannot be mixed. If no argument needs a wildcard, pass plain values - eq() everywhere is noise with identical behaviour.
Explain what Mockito's ArgumentCaptor is for, how you create one and wire it into a verification, and how you read the captured value afterwards.
basics
~10 sAn ArgumentCaptor grabs the actual argument a mock received so you can assert on it. Create it with ArgumentCaptor.forClass(X.class) or @Captor, pass captor.capture() inside verify(...), then read captor.getValue() and assert normally.
In Mockito, what is an argument matcher such as any(), anyString() or anyInt(), and why would you stub or verify a call with one instead of passing a concrete expected value?
basics
~20 sA matcher is a placeholder used inside Mockito's when() or verify() saying 'any argument fitting this description' instead of one exact value. any() matches anything, anyString() any non-null String, anyInt() any int. Use them when the value is irrelevant or unpredictable.
Mockito throws InvalidUseOfMatchersException when a stubbed call mixes an argument matcher such as ArgumentMatchers.anyInt() with a plain literal argument. Explain the rule this violates and how Mockito's argument matchers are implemented under the hood.
basics
~20 sMatchers do not return values you pass in. Each one pushes a matcher object onto a thread-local stack and returns a dummy (0, false, null). Mockito only sees dummies, so per call all arguments must be matchers or none. Wrap literals in eq().
Mockito's built-in matchers cannot express a condition like 'an Order whose total exceeds 100 and whose status is PENDING'. How do you match an argument on an arbitrary condition when stubbing or verifying with Mockito?
basics
~20 sUse argThat(ArgumentMatcher) with a predicate: verify(repo).save(argThat(o -> o.total() > 100 && o.status() == PENDING)). ArgumentMatcher is a functional interface with one boolean matches(T) method, so a lambda works. It composes with the built-in matchers in the same call.
You need a test to prove that a mocked collaborator's open() method was called before its write() method. How do you express that ordering in Mockito, and why are two ordinary verify() calls not enough?
basics
~20 sCreate an ordering handle with InOrder inOrder = inOrder(mock), then call inOrder.verify(mock).open() followed by inOrder.verify(mock).write(...). Plain verify() only checks that each call happened at all; it ignores sequence, so it passes even if write ran first.
In the Mockito mocking library, how do you assert that a method was called on a mock, and how do you assert it was called an exact number of times?
basics
~20 sUse verify(mock).method(args) - it asserts exactly one matching call. For other counts pass a mode: verify(mock, times(3)).method(args). Arguments match by equals or by matchers. A mismatch throws an assertion error showing wanted versus actual invocations.
In the Mockito mocking library, how do you assert that a collaborator was not touched at all during a test, and how is that different from asserting that one particular method was not called?
basics
~20 sUse verifyNoInteractions(mock) - it fails if any method at all was called on that mock. Asserting one method was not called is verify(mock, never()).method(args), which is scoped to that method and those arguments and says nothing about the rest of the mock.
In a Mockito test the collaborator is invoked from a background thread, so a plain verify() runs before the call happens. How does verify(mock, timeout(1000)).method() solve that, and what is Mockito doing during that second?
basics
~20 stimeout(ms) wraps the verification mode in a retry loop: Mockito re-checks the mock's recorded calls about every 10 ms until the check passes or the budget expires, then rethrows the last failure. It returns the moment it succeeds, so the number is an upper bound, not a sleep.
Mockito offers both verify(mock, timeout(200)).send(msg) and verify(mock, after(200)).send(msg). How does each one spend those 200 milliseconds, and what can one catch that the other cannot?
basics
~20 stimeout(200) polls and returns as soon as the verification passes, so it is an upper bound. after(200) always waits the whole 200 ms and only then asserts, so it can catch extra or late calls that timeout would have already passed over.
In a Mockito test, what value comes back when you call a method on a mock that you never stubbed, and what part of Mockito decides that value?
basics
~10 sThe mock's default answer decides. Mockito's built-in default, Answers.RETURNS_DEFAULTS, gives 0 for numeric primitives, false for boolean, an empty collection, Optional or Stream for those types, and null for every other object. Nothing throws.
What does Mockito's Answers.RETURNS_DEEP_STUBS do, how do you turn it on for a mock, and which failure does it exist to prevent?
basics
~20 sIt makes a mock auto-create and cache a mock for each mockable return type, so chained calls like when(a.getB().getC()).thenReturn(x) work instead of throwing NullPointerException on the second link. Enable with @Mock(answer = Answers.RETURNS_DEEP_STUBS) or mock(A.class, RETURNS_DEEP_STUBS).
Older Mockito versions could not mock a final class or a final method. Explain the mechanism behind that limitation and what the inline mock maker does differently.
basics
~20 sThe classic mock maker generates a runtime subclass and overrides methods, and Java forbids subclassing a final class or overriding a final method. The inline mock maker instead attaches a Java agent and rewrites the loaded class's own bytecode, so no subclass is needed.
A class you are testing creates a collaborator with `new` inside one of its methods, so there is no seam to inject a test double. How does Mockito's `mockConstruction(Class)` API let you take control of that instance, and what exactly does it intercept?
basics
~20 sMockito.mockConstruction(Foo.class) opens a scope in which every new Foo(...) on the current thread returns a Mockito mock instead of a real object, and the real constructor body never runs. Closing the scope restores normal construction.
Your code calls a static utility method that returns the current time, and you need it to return a fixed value inside one test. How do you stub that static call with Mockito, and how do you keep the stubbing from leaking outside the test?
basics
~20 sOpen Mockito.mockStatic(TheClass.class) in a try-with-resources block; inside it, stub with mocked.when(TheClass::method).thenReturn(value). While the scope is open all static methods of that class are mocked on the current thread, and closing the scope restores the real implementations.
A Java unit test fails with Mockito's UnnecessaryStubbingException even though every assertion passed. What exactly triggers that exception, when is it reported, and how should you fix it?
basics
~20 sIt means a stubbing you declared was never matched by any call during the test. Under strict stubbing Mockito reports it after the test, pointing at the stubbing's line. The fix is usually to delete the stubbing or move it into the test that actually needs it — not to switch strictness off.
When you write a unit test for a service class that has several collaborators, how do you decide which of them to replace with Mockito mocks and which to construct for real?
basics
~20 sMock the boundary: collaborators that leave the process or are slow, nondeterministic or hard to set up (repositories, HTTP clients, clocks, message publishers). Construct everything else for real: value objects, DTOs, enums, collections, pure helpers. Real is the default; a mock needs a reason.
In Mockito every collaborator you build with Mockito.mock() is called a "mock". When you write when(...).thenReturn(...) versus when you write verify(...), which test-double role is that object actually playing, and why does it matter which one a given test uses?
basics
~20 sMockito.mock() is only a mechanism. Stubbing with when/thenReturn puts the object in a stub role: it supplies input and your assertion checks the result. verify() puts it in a mock role: the call itself is the thing being asserted. Pick one role per collaborator.
Mockito's Strictness enum has three values: LENIENT, WARN and STRICT_STUBS. What does each one change about how a test behaves, and why was strict stubbing introduced?
basics
~20 sLENIENT does no stubbing checks (old Mockito 1.x behaviour). WARN only logs hints about unused or mismatched stubbings. STRICT_STUBS fails the test: a stubbing that was never used is an error, and calling a stubbed method with arguments matching no stubbing fails at the call site instead of returning null.
Under Mockito's strict stubbing, a test throws PotentialStubbingProblem in the middle of the code under test. What condition produces that exception, and why is it considered more useful than the older behaviour it replaced?
basics
~20 sIt fires when the code calls a mock method that IS stubbed, but with arguments matching none of its stubbings. Mockito fails right at that call, showing stubbed versus actual arguments. Previously the call silently returned null, so the test failed later with an unrelated NullPointerException.