mercredi 6 avril 2016

how to mock a fluent api with static method calls in it?

I have scenario like i need to test a method which uses a fluent api with static method calls in it. I am able to mock upto the static call but i dont know how to mock the whole fluent method calls and return the corresponding output.

Scenario:

Test class:

 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 class:

 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 case:

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

}

As you can see the code , I am able to mock PaltformRuntime.getInstance() but if i try to mock PaltformRuntime.getInstance().getElementRegistry().getElement() and returns customer object i am getting an null pointer exception in getElementRegistry() call. I am able to mock fluent api without any static methods in it.But in this sceanrio i got stuck. I dont know what am missing ? please suggest how to mock the fluent api with static methods in it.

Aucun commentaire:

Enregistrer un commentaire