Mockito Default Return Values | Java Fresher Interview
Fast recall
Quick revision
Core answer
Answer. With RETURNS_DEFAULTS, numeric primitives are zero, boolean is false, and many common container types such as collections and Optional are empty. Many other reference types return null. Strict stubbing can report unnecessary or mismatched stubs, but it does not make every ordinary unstubbed call throw.Interview-ready guide
Interview answer
An unstubbed method on a Mockito mock returns the value chosen by the mock's default Answer, normally RETURNS_DEFAULTS. Numeric primitives return zero, booleans return false, and Mockito supplies empty values for several common containers such as collections and Optional. Many other object-returning methods return null. For example, an unstubbed repository method returning Optional gives Optional.empty(), so calling orElseThrow() fails in the service rather than at the mock call. This convenience keeps setup small, but it can hide a forgotten stub. Strict stubbing helps find unused stubs and some argument mismatches; it does not make every unstubbed call illegal. I explicitly stub any result that controls the path being tested.
Mockito Default Return Values | Java Fresher Interview
Direct Answer
An unstubbed Mockito method uses the mock's default Answer. With RETURNS_DEFAULTS, numeric primitives are zero, boolean is false, and many common container types such as collections and Optional are empty. Many other reference types return null. Strict stubbing can report unnecessary or mismatched stubs, but it does not make every ordinary unstubbed call throw.
Code Example
interface Catalog {
int itemCount();
boolean available();
Optional<String> featuredName();
List<String> tags();
URI homepage();
}
@Test
void showsDefaultAnswers() {
Catalog catalog = mock(Catalog.class);
assertEquals(0, catalog.itemCount());
assertFalse(catalog.available());
assertEquals(Optional.empty(), catalog.featuredName());
assertEquals(List.of(), catalog.tags());
assertNull(catalog.homepage());
}
Common Mistakes & Pitfalls
- Assuming all objects return null: common containers such as
Optionaland collections have empty defaults. - Assuming strict mode rejects every unstubbed call: strictness focuses on stubbing quality and mismatches, not a blanket unstubbed-call ban.
- Letting defaults select the scenario: explicitly stub values that drive the branch under test.
- Using deep stubs casually: they can couple the test to a long implementation chain.
- Reading a later NPE as the root problem: trace it back to a missing arrangement when a reference default was null.
Check your understanding
Answer these without looking back at the article.
- What is RETURNS_DEEP_STUBS and why is it generally discouraged?
- What does Mockito return for Optional return types?
- How do you change the default answer strategy for a mock?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.