【发布时间】:2016-04-06 11:32:32
【问题描述】:
我有一个场景,比如我需要测试一个方法,该方法使用带有静态方法调用的 fluent 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() 并返回客户对象我在 getElementRegistry() 调用中得到一个空指针异常。 我可以在没有任何静态方法的情况下模拟流利的 api。但是在这个场景中我被卡住了。 我不知道缺少什么?请建议如何使用其中的静态方法模拟流利的 api。
【问题讨论】:
-
你为什么不使用模拟来代替
PaltformRuntime.getInstance()以便“实例”是模拟? -
是的,实例是一个模拟,我试图检查我是否能够模拟到 PaltformRuntime.getInstance()。我能够做到这一点。如果我尝试像 When ( PaltformRuntime.getInstance().getElementRegistry().getElement()).then return(customer);我收到空指针异常
标签: unit-testing testing mocking mockito powermock