Method chaining like foo.bar().baz() requires mocking each intermediate return value, because each call in the chain returns a separate object that must itself be a configured mock.
Key Points: • Mock the root object, then stub its first method to return a second mock representing the intermediate result. • Stub the second mock's method to return the final value or another mock, continuing down the chain. • Mockito's RETURNS_DEEP_STUBS answer can auto-generate intermediate mocks so you can stub the whole chain in one line. • Deep stubbing is convenient but can hide poor design - long chains often violate the Law of Demeter. • Prefer refactoring the code to reduce chaining before reaching for deep stubs, when practical.
Example: To stub foo.bar().baz() manually, you'd write Bar barMock = mock(Bar.class); when(foo.bar()).thenReturn(barMock); when(barMock.baz()).thenReturn(expectedValue).
Code Example:
Foo foo = mock(Foo.class);
Bar bar = mock(Bar.class);
when(foo.bar()).thenReturn(bar);
when(bar.baz()).thenReturn("result");
assertEquals("result", foo.bar().baz());Interview Tip: A concise interview answer is:
"For chained calls I mock every object in the chain individually and stub each hop to return the next mock, or use Mockito.mock(Foo.class, RETURNS_DEEP_STUBS) to have it generate the intermediate mocks automatically. Deep stubs are convenient but heavy chaining is often a code smell worth refactoring."