How do you handle method chaining (e.g., foo.bar().baz()) in Mockito?

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

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).

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.

Last updated: 16 July 2026

Previous question: How would you mock dependencies that are passed to a method as parameters?

Next question: What is the difference between a stub and a mock?

More Mockito interview questions

All Mockito questions