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);
}
Advertisements
AssertJ, Java, JUnit, Maven, Mockito, Spring Framework

I against U

As we know now, that we should test each and every part of code, it is time to cover our application with tests. We can distinguish two main types of automatic tests:

  • unit
  • integration

Today, I’m going to show you how to set up environment for testing purpose using IntelliJ, maven, jUnit, AssertJ, Mockito and Spring Framework.

Continue reading