Can you explain Mockito's RETURNS_DEEP_STUBS and its use case?

RETURNS_DEEP_STUBS is a Mockito answer strategy that automatically generates mocks for every object returned along a method chain, so you can stub deeply nested calls without manually mocking each intermediate step.

Key Points: • Create the mock with mock(Foo.class, RETURNS_DEEP_STUBS) or use @Mock(answer = Answers.RETURNS_DEEP_STUBS). • You can then stub a whole chain in one line: when(foo.bar().baz()).thenReturn(value). • Internally Mockito creates and remembers a mock for each intermediate return value automatically. • It's convenient for legacy code with long chains, but it often masks a Law of Demeter violation worth refactoring. • Overusing deep stubs can make tests harder to read because the real object graph being mocked is hidden behind one-liners.

Example: For a.getB().getC().getName(), instead of mocking B and C individually, RETURNS_DEEP_STUBS lets you write when(a.getB().getC().getName()).thenReturn("test") directly.

Code Example:

A a = mock(A.class, RETURNS_DEEP_STUBS);
when(a.getB().getC().getName()).thenReturn("test");

assertEquals("test", a.getB().getC().getName());

Interview Tip: A concise interview answer is:

"RETURNS_DEEP_STUBS automatically creates intermediate mocks for every hop in a chained method call, so I can stub something like a.getB().getC().getName() in a single line instead of mocking each object manually. I use it sparingly, since long chains usually point to a design that could be simplified."