Unit testing 如何在fluent api中模拟静态方法调用?

Unit testing 如何在fluent api中模拟静态方法调用?,unit-testing,testing,mocking,mockito,powermock,Unit Testing,Testing,Mocking,Mockito,Powermock,我有一个场景,比如我需要测试一个使用fluent api的方法,其中包含静态方法调用。我能够模拟静态调用,但我不知道如何模拟整个fluent方法调用并返回相应的输出 情景: 测试等级: public class CustomerManagementService { /** * This method is used to verify the fluent api * @return */ public String fluentApiVerifica

我有一个场景,比如我需要测试一个使用fluent api的方法,其中包含静态方法调用。我能够模拟静态调用,但我不知道如何模拟整个fluent方法调用并返回相应的输出

情景:

测试等级:

 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()并返回customer对象,则在getElementRegistry()调用中会出现空指针异常。 我能够模拟fluent api,其中没有任何静态方法。但在这个sceanrio中,我被卡住了。
我不知道我错过了什么?请建议如何使用其中的静态方法模拟fluent api。

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);
}

为什么不使用模拟来代替
PaltformRuntime.getInstance()
,以便“instance”是一个模拟?是的,instance是一个模拟。我试图检查是否能够模拟PaltformRuntime.getInstance()。我能做到。如果我尝试模仿When(PaltformRuntime.getInstance().getElementRegistry().getElement()),然后返回(customer);我得到空指针异常请参见