Q:

Mockito chain function usage

When I am mocking chain of methods do I have to write them in the below format only
when(foo.getBar()).thenReturn(bar);
when(bar.getName()).thenReturn("Foo Bar");

or could I also use the below format? because both are working for me and I am asking this question because I was told that that my second (below) approach is wrong
when(foo.getBar()).thenReturn(bar);
when(foo.getBar().getName()).thenReturn("Foo Bar");

A:

The Mockito FAQ addresses this explicitly:

Can I stub chained getters?
when(mock.getA().getB()).thenReturn(...);

This sort of stubbing, e.g. mock to return mock, to return mock, etc. should be used very sporadically, ideally never. It clearly points out violation of the Law of Demeter. You don't want to mess with Demeter. Since you have been warned check out Mockito deep stubs.

From a technical standpoint, it is supported, partially because it is indistinguishable from this:
when(foo.getBar()).thenReturn(bar);
foo.getBar();
when(bar.getName()).thenReturn("Foo Bar");

...which can interfere with verification in the hopefully-unlikely event that you need to verify(foo, times(n)).getBar().

