我在模拟静态类TransportClient时遇到问题。 当我运行测试时,第一个要运行的工作正常,而第二个抛出NullPointerException。这不取决于哪一个是第一次运行。
我发现了原因。第二次 client.admin 返回null而不是模拟类adminClientMock:
1°试运行:
System.out.println(client) -> mock TransportClient
System.out.println(client.admin()) -> mock AdminClient
2°试运行:
System.out.println(client) -> mock TransportClient
System.out.println(client.admin()) -> null
有什么想法吗?我知道这不是很清楚,但课程电话很多。无论如何,我会感激任何帮助。
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();
.....
}
}