I have a problem mocking the static class TransportClient. When I run the tests, the first one to be run works fine, while the second throws a NullPointerException. This does not depend on which one is the first run.
I discovered the reason. The second time client.admin returns null instead the mock class adminClientMock:
1° Test run:
System.out.println(client) -> mock TransportClient
System.out.println(client.admin()) -> mock AdminClient
2° Test run:
System.out.println(client) -> mock TransportClient
System.out.println(client.admin()) -> null
Any idea? I know it is not really clear but the classes call are a lot. Anyway I will appreciate any kind of help.
public class ES{
private final Client client;
private ES() {
client = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress(esAddress));
}
public void method{
client.admin().indices().preparePutTemplate(template.getString("name"))
.setSource(mapping)
.execute().actionGet();
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({Settings.class, Configuration.class, TransportClient.class, InetSocketTransportAddress.class, ES.class})
public class ESTest{
private initMocks(){
// mock TransportClient class
PowerMockito.mockStatic(TransportClient.class);
TransportClient transportClientMock = PowerMockito.mock(TransportClient.class);
TransportClient.Builder mockTransportBuilder = PowerMockito.mock(TransportClient.Builder.class);
when(TransportClient.builder()).thenReturn(mockTransportBuilder);
when(mockTransportBuilder.settings(mockSettings)).thenReturn(mockTransportBuilder);
when(mockTransportBuilder.build()).thenReturn(transportClientMock);
Mockito.when(transportClientMock.addTransportAddress(any(InetSocketTransportAddress.class))).thenReturn(transportClientMock);
AdminClient adminClientMock = mock(AdminClient.class);
PowerMockito.when(transportClientMock.admin()).thenReturn(adminClientMock);
}
@Test
public void Test1(){
ES clientES = ES.getInstance();
.....
}
@Test
public void Test2(){
ES clientES = ES.getInstance();
.....
}
}