Mockito, Quick solutions

How to solve: mocking chained calls

I have met this issue several times, so I decided to give the simplest solution to you. You have probably had a situation, when you need to return one object, but it demanded mocking each and every object in the middle. You can avoid that by adding parameter to you mocked object like:

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Client elasticSearchClient;

@Mock
private ClusterHealthRequestBuilder healthRequestBuilder;

Currently you can use when() as presented below:

when(elasticSearchClient.admin().cluster().prepareHealth().setWaitForStatus(any())).thenReturn(healthRequestBuilder);

instead of mocking AdminClient, ClusterAdminClient and ClusterHealthRequestBuilder by hand:

@Mock
ptivate AdminClient admin;
@Mock
private ClusterAdminClient cluster;
@Mock
private ClusterHealthRequestBuilder clusterHealthRequestBuilder;

@Before
public void setUp() {
    when(elasticSearchClient.admin()).thenReturn(admin);
    when(admin.cluster()).thenReturn(cluster);
    when(cluster.prepareHealth()).thenReturn(clusterHealthRequestBuilder);
    when(clusterHealthRequestBuilder.setWaitForStatus(any())).thenReturn(healthRequestBuilder);
}