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 1 of 2

What is Mockito's ArgumentCaptor and what problem does it solve?

level: juniorimportance: must knowfreq 70%

answer

  1. Captures the actual argument for later assertion
  2. forClass(...) then capture() inside verify
  3. getValue() reads it back
  4. Assert specific fields, not the whole object
  5. Verification, not stubbing

basics

~10 s

ArgumentCaptor catches the actual value passed to a mock's method so you can store it and check it afterward with normal assertions, instead of only checking that the method was called.

solid answer

~40 s

An ArgumentCaptor is a Mockito helper that grabs (captures) the real argument a mock received during the test, so you can inspect it after the fact. You create one typed to the argument's class, pass captor.capture() in place of the argument inside a verify(...) call, then read it back with captor.getValue(). The problem it solves: sometimes you don't just want to assert that a collaborator was called, you want to assert details about a complex object that was built inside the code under test and handed to that collaborator. Without a captor you'd have to construct the exact expected object up front, which is brittle. The captor lets you pull the actual object out and assert only the fields you care about.

go deeper

for a junior

Can state that a captor grabs the actual argument passed to a mock so you can check it afterward, and knows the create/capture/getValue trio.

for a middle

Explains the brittleness problem with equals-based verify it solves and writes a correct verify(mock).method(captor.capture()) + getValue() flow.

for a senior

Articulates when captors beat argThat (post-hoc assertion, multiple values, readable assertions) and when they don't (stubbing conditions), and the verification-not-stubbing boundary.

for a principal

Can set team conventions on captor vs matcher usage, discuss readability/maintainability trade-offs, and flag overuse (capturing everything) as a test-design smell.

## The setup: what is a mock? In unit testing, a **mock** is a fake stand-in for a real object (a *collaborator*) that your code-under-test talks to. Mockito is a popular Java mocking library. You create a mock, let your code call it, and then **verify** which methods were called and with what arguments. The normal way to check arguments is to pass an expected value into `verify`: ```java verify(repository).save(expectedUser); ``` This only passes if the actual argument is **equal** (via `equals()`) to `expectedUser`. That works when you can easily build `expectedUser` yourself. But often the object handed to the collaborator is **constructed inside** the method you're testing — with generated IDs, timestamps, or fields you can't predict — so building an exactly-equal expected object up front is hard or brittle. ## What ArgumentCaptor is An **ArgumentCaptor** is a Mockito object whose job is to **remember the real value** that was passed to a mock's method during the test, so you can pull it out and assert on it afterward. Instead of saying "the argument must equal X", you say "give me whatever argument was actually passed, and I'll inspect it myself". ## How it works, step by step ```java // 1. Create a captor typed to the argument's class. ArgumentCaptor<User> captor = ArgumentCaptor.forClass(User.class); // 2. Run the code under test (it calls repository.save(...) internally). service.register("[email protected]"); // 3. Verify the call happened, using captor.capture() in the argument slot. verify(repository).save(captor.capture()); // 4. Read back the captured argument and assert on its fields. User saved = captor.getValue(); assertEquals("[email protected]", saved.getEmail()); assertNotNull(saved.getId()); ``` The key trick is in step 3: `captor.capture()` is a Mockito **matcher** that returns a placeholder (usually `null`/default) but has the side effect of recording the actual argument when the verification runs. After `verify` completes, `getValue()` returns what was really passed. ## When to reach for it - The argument is a **rich object built inside** the method (you want to assert specific fields, not the whole object). - You want **plain assertions** (AssertJ/JUnit) on the argument rather than encoding the check inside a matcher. - You want to assert on the argument **after** the call, possibly across multiple captured values. ## When NOT to If you just need to require an argument satisfies a condition (and reuse it for **stubbing**), an inline matcher like `argThat(...)` is often cleaner — see the captor-vs-matchers comparison. Captors are for verification + post-hoc inspection, not for stubbing return values.

  • Why might capturing be better than passing an expected object into verify?
    Because the object is often constructed inside the code under test with unpredictable fields (IDs, timestamps). Capturing lets you assert only the fields you care about instead of building an exactly-equal object.
  • Does capturing affect what the mock returns?
    No. capture() only records the argument; it doesn't change the mock's behavior or return value. Stubbing is separate (when(...).thenReturn(...)).

saying these in an interview costs you the question

  • Thinking ArgumentCaptor stubs behavior or sets return values — it only captures
  • Using capture() outside a verify/stub call and expecting it to record
  • Claiming you must build an exactly-equal expected object — that's the brittleness captors avoid
  • Confusing it with a Mockito matcher used for stubbing return values

context

open as a page

What are argument matchers in Mockito, and why would you use any() or eq() instead of passing a literal value when stubbing or verifying?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Argument matchers like any() or eq() tell Mockito how to match the arguments of a call instead of comparing exact values. Use any() when the value doesn't matter and eq(x) when you need a specific value but other arguments use matchers.

open as a page

What do the Mockito @Mock and @InjectMocks annotations do, and how do they work together in a unit test?

level: juniorimportance: must knowfreq 80%

basics

~10 s

@Mock creates a fake stand-in for a dependency. @InjectMocks creates the real object you are testing and pushes those mocks into it, so you can test it in isolation without its real collaborators.

open as a page

What does a freshly created, unstubbed Mockito mock return when its methods are called, for various return types?

level: juniorimportance: must knowfreq 75%

basics

~20 s

An unstubbed mock returns safe empty defaults: null for objects, 0 for numbers, false for booleans, and empty collections (an empty list/set/map, not null). So calling a method you didn't stub won't throw on its own.

open as a page

What is a mock object in Mockito, how do you create one, and why would you use it in a unit test?

level: juniorimportance: must knowfreq 85%

basics

~20 s

A mock is a fake stand-in for a real object that you create with Mockito.mock(SomeClass.class). You use it to replace a real collaborator so your test exercises only the one class you care about, without its dependencies doing real work.

open as a page

In Mockito, what is the difference between a mock and a spy?

level: juniorimportance: must knowfreq 78%

basics

~20 s

A mock is a fake object with no real behavior; every method returns a default (null, 0, false) until you stub it. A spy wraps a real object and runs its real code unless you stub a specific method.

open as a page

How do you make a Mockito mock throw an exception when a method is called, and what are the two ways to pass the exception?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Use when(mock.method()).thenThrow(...). You can pass either an exception instance (new IllegalStateException("x")) or an exception class (IllegalStateException.class), which Mockito instantiates for you.

open as a page

What does when(mock.method()).thenReturn(value) do in Mockito, and what happens if you call the stubbed method again or call a method you never stubbed?

level: juniorimportance: must knowfreq 80%

basics

~20 s

It tells a fake object: 'when this method is called, give back this value.' Call it again and you get the same value. Methods you never set up return harmless defaults like null, 0, or false.

open as a page

What does Mockito.verify do, and how does it differ from a stub set up with when/thenReturn?

level: juniorimportance: must knowfreq 80%

basics

~10 s

verify checks that a method was actually called on a mock (an interaction). when/thenReturn instead sets up what a method returns when called. verify asserts behavior happened; stubbing controls return values.

open as a page

How do you create and use an ArgumentCaptor, including the @Captor annotation?

level: middleimportance: must knowfreq 65%

basics

~10 s

Create one with ArgumentCaptor.forClass(Type.class), or declare a field with @Captor. Pass captor.capture() inside verify(mock).method(...), then read the captured value with captor.getValue().

open as a page

Explain Mockito's rule that if one argument uses a matcher, all arguments must use matchers. Why does this rule exist, and how do you satisfy it for a literal argument?

level: middleimportance: must knowfreq 75%

basics

~20 s

If you use a matcher like any() for one argument of a call, you must use matchers for every argument of that call. For a plain value, wrap it in eq(). Mixing a matcher with a raw literal throws InvalidUseOfMatchersException.

open as a page

How do you enable Mockito's @Mock and @InjectMocks annotations in a JUnit 5 test, and what alternatives exist?

level: middleimportance: must knowfreq 70%

basics

~10 s

Add @ExtendWith(MockitoExtension.class) to the test class. Without it (or a manual MockitoAnnotations.openMocks(this) call in setup), the annotated fields stay null.

open as a page

How does the @Mock annotation relate to Mockito.mock(Class), and what is required to make @Mock fields actually become mocks?

level: middleimportance: must knowfreq 70%

basics

~10 s

@Mock is shorthand for Mockito.mock(SomeClass.class) on a field. But the annotation does nothing by itself — you must initialize it, either with @ExtendWith(MockitoExtension.class) (JUnit 5) or MockitoAnnotations.openMocks(this) in a setup method.

open as a page

Why can't you use when(...).thenThrow(...) for a void method, and how do you stub a void method to throw?

level: middleimportance: must knowfreq 65%

basics

~10 s

A void method returns nothing, so you can't pass its call into when(...). Use the do-form instead: doThrow(new RuntimeException()).when(mock).doStuff();

open as a page

How do you verify a mock was called with specific arguments, including using matchers and ArgumentCaptor?

level: middleimportance: must knowfreq 68%

basics

~20 s

Pass the expected argument to verify, e.g. verify(repo).save(user) — it must equal the actual argument. Use matchers like eq(), any(), argThat() for flexible matching, or ArgumentCaptor to grab the real argument and assert on it.

open as a page

What are VerificationModes in Mockito (times, never, atLeastOnce, atLeast, atMost) and when would you use each?

level: middleimportance: must knowfreq 72%

basics

~10 s

A VerificationMode says how many times a call should have happened. times(n) = exactly n, never() = zero, atLeastOnce() = one or more, atLeast(n)/atMost(n) = bounds. Default verify(mock) means times(1).

open as a page

Why should a MockedStatic be used inside a try-with-resources block, and what goes wrong if you don't close it?

level: seniorimportance: must knowfreq 60%

basics

~20 s

MockedStatic is AutoCloseable. Opening it in try-with-resources guarantees it closes at the end of the test. If you forget to close it, the static stays mocked and leaks into later tests on the same thread, causing confusing failures.

open as a page

Why must you usually stub a Mockito spy with doReturn().when() instead of when().thenReturn()?

level: seniorimportance: must knowfreq 64%

basics

~10 s

Because when(spy.foo()).thenReturn(x) actually runs the real foo() first (Java evaluates the argument before when sees it). If foo() has side effects or throws, your stub line breaks. doReturn(x).when(spy).foo() never calls the real method.

open as a page

Why does Mockito have the doReturn(...).when(mock).method() form in addition to when(mock.method()).thenReturn(...), and when must you use it?

level: seniorimportance: must knowfreq 50%

basics

~20 s

when(mock.method()) actually calls the method first to set up the stub, which is a problem for spies (real objects) and impossible for void methods. doReturn(...).when(mock).method() avoids calling the real method, so use it for spies and void/throwing cases.

open as a page

What is BDDMockito, and how does it change the way you write Mockito stubs and verifications?

level: juniorimportance: should knowfreq 45%

basics

~10 s

BDDMockito is a Mockito helper class that renames the usual stubbing methods so tests read like Given-When-Then. Instead of when(mock.foo()).thenReturn(x) you write given(mock.foo()).willReturn(x). It does the same thing, just with friendlier wording.

open as a page

What is the difference between getValue() and getAllValues() on an ArgumentCaptor, and how do you capture arguments across multiple calls?

level: middleimportance: should knowfreq 50%

basics

~10 s

getValue() returns the last captured argument; getAllValues() returns every captured argument as a list in call order. Use getAllValues() with verify(mock, times(n)) to check a sequence of calls.

open as a page

How do you correctly match null and nullable arguments in Mockito, and how does that interact with typed any(Class) and primitive matchers?

level: middleimportance: should knowfreq 45%

basics

~20 s

To match a null argument use isNull(); to match null or a value use nullable(Type.class) or bare any(). any(Foo.class) and anyString()/anyInt() do NOT match null, so don't rely on them when the code might pass null.

open as a page

Map the core BDDMockito methods to their classic Mockito equivalents, including stubbing return values, throwing, and verification.

level: middleimportance: should knowfreq 50%

basics

~10 s

given() replaces when(); willReturn() replaces thenReturn(); willThrow() replaces thenThrow(); and then(mock).should() replaces verify(mock). Same behavior, different names that read as Given-When-Then.

open as a page

How do you mock a static method with Mockito, and what does Mockito.mockStatic return?

level: middleimportance: should knowfreq 55%

basics

~10 s

Call Mockito.mockStatic(SomeClass.class). It returns a MockedStatic handle you use to stub the static methods. While that handle is open, real static calls are replaced by your stubs; closing it restores the real behavior.

open as a page

What is the inline mock-maker, why is it required to mock statics, and how do its versions/configuration differ across Mockito releases?

level: middleimportance: should knowfreq 40%

basics

~20 s

The inline mock-maker is Mockito's engine that rewrites bytecode at runtime so it can intercept static (and final) methods. mockStatic only works with it. It's the default in Mockito 5+; in older versions you added the mockito-inline dependency.

open as a page

What is the difference between @Mock and @Spy, and how do they each behave when injected via @InjectMocks?

level: middleimportance: should knowfreq 50%

basics

~20 s

A @Mock is a complete fake — every method returns a default until you stub it. A @Spy wraps a real object and calls real methods by default, letting you override just some. @InjectMocks can inject either into the object under test.

open as a page

How do you create a Mockito spy, and what are the ways to do partial mocking on it?

level: middleimportance: should knowfreq 60%

basics

~10 s

Create a spy with Mockito.spy(realObject) or the @Spy annotation (with @ExtendWith(MockitoExtension.class) or initMocks). Partial mocking means the spy runs real methods except the few you stub.

open as a page

How do you make a mocked method return different values on consecutive calls, and what happens after the listed values run out?

level: middleimportance: should knowfreq 55%

basics

~10 s

Chain them: thenReturn(a, b, c) or thenReturn(a).thenReturn(b).thenReturn(c). The first call returns a, the second b, the third c. After the list runs out, every later call keeps returning the last value.

open as a page

When should you prefer ArgumentCaptor over an argThat matcher, and vice versa?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Use a captor to assert on an argument after the call with normal assertions, especially for complex objects or sequences. Use argThat when you need the condition during stubbing or want the matching logic inline as part of verify.

open as a page

How do you match a complex argument by some of its fields using argThat(), and what are the trade-offs versus ArgumentCaptor?

level: seniorimportance: should knowfreq 55%

basics

~20 s

argThat() lets you pass a custom predicate that decides whether an argument matches — e.g. accept any Order whose total is over 100. Use it for inline rules; use ArgumentCaptor when you want to grab the actual argument and run rich assertions on it.

open as a page

showing 1–30 of 47