Mock within a mock
Mocks returning mocks, returning mocks; unit testing legacy systems sure is a drag.
Foo foo = mock(Foo.class);
Bar bar = mock(Bar.class);
when(foo.getBar()).thenReturn(bar);
when(bar.getName()).thenReturn("deep");
Fortunatly, Mockito has this cool feature called deep stubs, that can ease the pain. The previous code snippet is equivalent to the following:
Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
when(mock.getBar().getName(), "deep");
Ain’t that neet?
Of course, this feature should only be used to test legacy code since all your fresh code respects the Law of Demeter. Right? Don’t forget that every time a mock returns a mock a fairy dies.