Tuesday, December 4, 2018

PowerMockito: Mocking static method

Mocking Static method and invoking private static method:

PowerMockito.mockStatic(ClassWithPrivateStaticMethods.class);
PowerMockito.when(ClassWithPrivateStaticMethods.class, "getParam", Mockito.anyString()).thenReturn("dummy");

but the best way is

PowerMockito.spy(ClassWithPrivateStaticMethods.class);
PowerMockito.doReturn("dummy").when(ClassWithPrivateStaticMethods.class, "getParam", Mockito.anyString())
String finalResult = Whitebox.invokeMethod(ClassWithPrivateStaticMethods.class, "getDetail", Mockito.anyString());


More details on:

https://initcodes.blogspot.com/2018/05/powermockito-mocking-one-static-method.html


We can Invoke the private static methods with whitebox from mockito which uses reflection api


public void testLoadLanguageCodeFile()
          throws WorldlingoException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    //testing correct file path    String path = "/webapps/worldlingo/conf/settings/";
    PowerMockito.mockStatic(SystemSettings.class);
    HashMap<String, String> hash_map = new HashMap<String, String>();
    SystemSettings ssmock = Mockito.mock(SystemSettings.class);
    Mockito.when(SystemSettings.GetInstance()).thenReturn(ssmock);
    Mockito.when(ssmock.getLangCodePath()).thenReturn(path);
    Method m = Whitebox.getMethod(MicrosoftEngine.class,"loadLanguageCodeFile", HashMap.class);
    m.invoke(null, hash_map);
    assertTrue((hash_map.containsKey("de") && hash_map.containsKey("ar")) || hash_map.isEmpty());

    //testing incorrect file path    path = "/webapps/worldlingo/conf";
    Mockito.when(ssmock.getLangCodePath()).thenReturn(path);
    hash_map = new HashMap<String, String>();
    try {
      m = Whitebox.getMethod(MicrosoftEngine.class, "loadLanguageCodeFile", HashMap.class);
      m.invoke(null, hash_map);
    }
    catch (InvocationTargetException e){
      String result =  e.getTargetException().toString();
      assertEquals("java.lang.NullPointerException",result);
    }
  }

} // MicrosoftEngineTest



Mockito important tips:

do answer:
      @Test
 public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
 }



Mockito.doAnswer(new Answer() {
      @Override
      public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
        // this will be used to assert the status response
        key[0] =  (String)invocationOnMock.getArguments()[0];
        value[0] =  (String) invocationOnMock.getArguments()[1];
        return null;
      }
    }).when(robMock).addHeader(Mockito.anyString(),Mockito.anyString());


    PowerMokito:
       PowerMockito.whenNew(SFramework.class).withNoArguments().thenReturn(sfMock);

       https://github.com/powermock/powermock/wiki/Mockito#mocking-static-method


    https://initcodes.blogspot.com/2018/07/powermockito-javasecuritynosuchalgorith.html