Video in progress

Strong Middle 🧪 Testing

What does a Mockito mock return from methods you haven't stubbed, and when does RETURNS_DEEP_STUBS become a trap?

By default (RETURNS_DEFAULTS): null for objects, 0/false for primitives, and an empty value for collections, Optional and Stream. RETURNS_DEEP_STUBS stubs a chain like a.getB().getC() in one line, but it hides a tangled design and nails the test to the internal structure.

📖 Answer

Many "mysterious" NPEs come from exactly this default:

OrderRepository repo = mock(OrderRepository.class);
repo.findAll();          // an empty List, not null
repo.findById(1L);       // Optional.empty()
repo.count();            // 0
repo.findEntity(1L);     // null, then an NPE inside the service

If the NPE is there because you forgot a stub, the message tells you nothing. mock(Repo.class, RETURNS_SMART_NULLS) gives a clearer error in that case: "this value came from the unstubbed findEntity call".

Now deep stubs:

Order order = mock(Order.class, RETURNS_DEEP_STUBS);
when(order.getCustomer().getAddress().getCity()).thenReturn("Toshkent");

It looks convenient, but this test freezes the fact that the service reaches three levels deep with order.getCustomer().getAddress().getCity(). If the code moves to order.deliveryCity(), the test breaks. On top of that, with generic return types (for example, List<T>), a deep stub doesn't always give the mock you expect.

Mockito's own documentation warns about this too: if a mock has to return a mock, something is wrong with the design. The fix is usually not to mock plain data objects like Order and Customer at all, and build real ones with a builder. I use deep stubs only with third-party libraries that have a fluent API (builder chains).