skip to content

Mockito offers `mockConstructionWithAnswer(Class, Answer, Answer...)` alongside the initializer-based `mockConstruction`. What does that variant actually do with the answers you pass, and where does it fit?

level: seniorimportance: nice to knowfreq 18%

answer

  1. sets the mock's DEFAULT ANSWER, not a stub
  2. answer N → construction N; last answer repeats
  3. uniform across all methods
  4. return type must match or it fails
  5. initializer for per-method behaviour

basics

~20 s

It intercepts construction like mockConstruction, but instead of a stubbing callback you supply default Answers: the first Answer backs the first constructed instance, each further Answer the next construction, and the last one is reused for all remaining instances. It applies to every method, not a chosen one.

solid answer

~50 s

`mockConstructionWithAnswer(Foo.class, defaultAnswer, moreAnswers...)` builds each intercepted instance as a mock whose *default answer* comes from the list: construction 1 gets the first answer, construction 2 the second, and once the list is exhausted the final answer is reused for every subsequent construction. Because it sets a default answer rather than stubbing methods, it is method-agnostic: every call on that instance goes through the answer. That makes it a good fit for "make everything return a canned value", "make all calls throw", or handing constructed mocks a smarter default such as an answer that echoes arguments. ```java try (MockedConstruction<Foo> m = Mockito.mockConstructionWithAnswer( Foo.class, invocation -> "first", invocation -> "rest")) { /* ... */ } ``` When different methods on the same instance need different values, go back to `mockConstruction` with a `MockInitializer` — that is the expressive form.

code

java · 11 lines
java
Answer<Object> boom = invocation -> { throw new IOException("cold start"); };
Answer<Object> ok   = invocation -> "payload";

try (MockedConstruction<Downloader> mocked =
         Mockito.mockConstructionWithAnswer(Downloader.class, boom, ok)) {

    String result = retryingService.fetch();   // constructs twice

    assertEquals("payload", result);
    assertEquals(2, mocked.constructed().size());
}

go deeper

for a junior

Know it exists and that it sets a blanket behaviour for constructed instances; the initializer form is the one to learn first.

for a middle

State the per-construction mapping and the repeat-the-last rule, and contrast an Answer with a stub.

for a senior

Choose between it and an initializer on readability grounds, and anticipate return-type mismatches on wide classes.

for a principal

Treat repeated need for construction-ordinal behaviour as evidence that the construction sequence is real domain logic deserving an explicit collaborator.

## Answers versus stubs A Mockito *stub* binds one method call pattern to one outcome (`when(foo.name()).thenReturn("a")`). A Mockito *Answer* is a callback consulted for calls that have no stub — the mock's default behaviour. Ordinary mocks use `RETURNS_DEFAULTS`, which yields null, 0, false or empty. `mockConstructionWithAnswer` lets you replace that default for objects your test never gets to configure by hand. ## The varargs semantics The signature is `mockConstructionWithAnswer(Class<T> type, Answer defaultAnswer, Answer... additionalAnswers)`. The mapping is by construction ordinal, not by method call: 1. First `new Foo(...)` inside the scope → mock whose default answer is `defaultAnswer`. 2. Second construction → first element of `additionalAnswers`. 3. Third construction → second element, and so on. 4. Once the list runs out, the **last** answer supplied is reused for every further construction. This is the same "consume, then repeat the tail" rule Mockito uses for consecutive stubbing, applied to construction sequence. It reads well for a test like "the first client fails, all later clients succeed". ## What you give up Because an Answer sits below the method level, you cannot say "`isOpen()` returns true but `read()` throws" without writing that branching inside the Answer itself, inspecting `invocation.getMethod()`. At that point a `MockInitializer` with two `when(...)` lines is shorter and far more readable. The practical rule: use `mockConstructionWithAnswer` when the behaviour is uniform across methods (a canned value, a thrown exception, an argument-echoing answer); use `mockConstruction` with an initializer when the behaviour is per-method. ## Return-type safety An Answer must produce something assignable to each method's return type. A lambda that always returns a `String` will fail the moment the code calls a method returning `int` or a domain object. Uniform answers are therefore safest on narrow classes, or when the answer inspects the invocation and reacts to the return type — which is exactly what Mockito's own `RETURNS_SMART_NULLS` and `CALLS_REAL_METHODS` do, and both can be passed here. ## Interaction with the rest of the scope Everything else about the scope is unchanged: the returned object is still a `MockedConstruction<T>`, still thread-local, still `AutoCloseable`, and `constructed()` still lists the instances in creation order so you can verify interactions afterwards. You can also stub an instance further after pulling it out of `constructed()`, provided the code under test has not used it yet — explicit stubs win over the default answer. ## Where it earns its place The honest answer in an interview is that it is a convenience overload, not a distinct capability. Reach for it when the test's intent is "whatever this internally-created thing is asked, give it this", or when you want one construction to behave differently from the rest without writing a `getCount()` switch. Anything more specific belongs in an initializer, and anything much more specific than that is a hint that the class should be taking the collaborator as a constructor parameter instead.

  • What happens if the code under test constructs the class five times but you supplied only two answers?
    The first construction uses the first answer, the second uses the second, and constructions three through five all reuse the last answer supplied. Mockito repeats the tail rather than falling back to the standard defaults, which mirrors how consecutive stubbing behaves when calls outnumber the configured returns.
  • Why can a single-lambda answer cause a runtime failure on a class with mixed return types?
    The answer is consulted for every method, so a lambda that always returns a String is applied to a method declared to return `int` or a domain object, and Mockito rejects the incompatible value. Either narrow the usage to methods with one return type, or inspect `invocation.getMethod().getReturnType()` inside the answer and branch.

saying these in an interview costs you the question

  • Thinking the extra answers are consecutive returns for repeated calls on one instance rather than per construction.
  • Believing it lets you stub individual methods.
  • Expecting constructions past the supplied answers to revert to default nulls.
  • Assuming it removes the need to close the scope.

context