skip to content

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 pageshow

explore

questions

114 · 6 sections

You 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?

level: juniorimportance: must knowfreq 78%
basics
~20 s

No 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
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.

open as a page

In Mockito, what does the @InjectMocks annotation do to the field it is placed on, and where does it get the values it injects?

level: juniorimportance: must knowfreq 70%
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.

open as a page

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?

level: juniorimportance: must knowfreq 68%
basics
~20 s

On 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.

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~20 s

Both 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Chain 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.

open as a page

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.

level: juniorimportance: must knowfreq 58%
basics
~10 s

when(...) 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.

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Use 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.

open as a page

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.

level: juniorimportance: must knowfreq 78%
basics
~10 s

Write 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.

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~10 s

Use 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.

open as a page

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?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Use 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.

open as a page

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.

level: juniorimportance: must knowfreq 70%
basics
~10 s

An 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A 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.

open as a page

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.

level: middleimportance: must knowfreq 72%
basics
~20 s

Matchers 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().

open as a page

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?

level: middleimportance: must knowfreq 45%
basics
~20 s

Use 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.

open as a page

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?

level: juniorimportance: must knowfreq 40%
basics
~20 s

Create 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.

open as a page

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?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Use 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.

open as a page

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?

level: juniorimportance: must knowfreq 52%
basics
~20 s

Use 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.

open as a page

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?

level: middleimportance: must knowfreq 45%
basics
~20 s

timeout(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.

open as a page

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?

level: middleimportance: must knowfreq 38%
basics
~20 s

timeout(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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

The 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.

open as a page

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?

level: middleimportance: must knowfreq 38%
basics
~20 s

It 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).

open as a page

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.

level: middleimportance: must knowfreq 58%
basics
~20 s

The 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.

open as a page

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?

level: middleimportance: must knowfreq 42%
basics
~20 s

Mockito.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.

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~20 s

Open 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~20 s

It 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Mock 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.

open as a page

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?

level: middleimportance: must knowfreq 56%
basics
~20 s

Mockito.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.

open as a page

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?

level: middleimportance: must knowfreq 58%
basics
~20 s

LENIENT 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.

open as a page

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?

level: middleimportance: must knowfreq 48%
basics
~20 s

It 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.

open as a page