我有这样的场景,我需要测试一个方法,该方法使用带有静态方法调用的流畅api。我能够模拟静态调用,但我不知道如何模拟整个流畅的方法调用并返回相应的输出。
情景:
测试类:
public class CustomerManagementService {
/**
* This method is used to verify the fluent api
* @return
*/
public String fluentApiVerificationWithStatic(){
Customer customer=PaltformRuntime.getInstance().getElementRegistry().getElement();
return customer.getName();
}
}
PaltformRuntime类:
public class PaltformRuntime {
public static PaltformRuntime paltformRuntime = null;
public static PaltformRuntime getInstance(){
if(null == paltformRuntime) {
paltformRuntime = new PaltformRuntime();
}
return paltformRuntime;
}
public PaltformRuntime getElementRegistry(){
return paltformRuntime;
}
public Customer getElement(){
Customer c=new Customer();
return c;
}
}
测试用例:
@Test
public void fluentVerificationwithStatic() throws Exception {
PaltformRuntime instance = PaltformRuntime.getInstance();
PowerMockito.mockStatic(PaltformRuntime.class);
PowerMockito.when(PaltformRuntime.getInstance()).thenReturn(instance);
CustomerManagementService customerManagementService=new CustomerManagementService();
String result = customerManagementService.fluentApiVerificationWithStatic();
//assertEquals(customer.getName(), result);
}
正如你可以看到的代码,我可以模拟 PaltformRuntime.getInstance()但是如果我试图模拟 PaltformRuntime.getInstance()。getElementRegistry()。getElement()< / strong>并返回customer对象我在getElementRegistry()调用中得到一个空指针异常。 我能够在没有任何静态方法的情况下模拟流畅的api。但是在这个场景中我被卡住了。 我不知道失踪了什么?请建议如何使用静态方法模拟流畅的api。
答案 0 :(得分:0)
对PaltformRuntime
实例
@Test
public void fluentVerificationwithStatic() throws Exception {
Customer customer = new Customer();
PaltformRuntime instance = Mockito.mock(PaltformRuntime.class, RETURNS_DEEP_STUBS);
when(instance.getElementRegistry().getElement()).thenReturn(customer);
PowerMockito.mockStatic(PaltformRuntime.class);
PowerMockito.when(PaltformRuntime.getInstance()).thenReturn(instance);
CustomerManagementService customerManagementService=new CustomerManagementService();
String result = customerManagementService.fluentApiVerificationWithStatic();
assertEquals(customer.getName(), result);
}