0

In order to mock static methods for unit testing in Java we can either use PowerMock or we Can use mockStatic of Mockito. I already know that need to mock static method means code smell and I should refactor the original code but that is not possible as of now.

Sample Class to be Tested

public class classToBeTested{

//Some Code

public static String methodToBeTested() {
// Some Code
}

}

Testing Using Mockito-Inline (Mockito MockStatic)

public class TestClassToBeTested{
private MockedStatic<classToBeTested> mockedClassToBeTested;

@Test
public void testmethodToBeTested() {

mockedClassToBeTested =
Mockito.mockStatic(classToBeTested.class);
mockedClassToBeTested.when(classToBeTested::methodToBeTested)
.thenReturn("Some Value");

// extra code for testing
}
}

Testing Using PowerMock

public class TestClassToBeTested{

@Test
public void testmethodToBeTested() {

PowerMockito.mockStatic(classToBeTested.class);
when(classToBeTested.methodToBeTested())
.thenReturn("Some Value");

// extra code for testing
}
}

So which mocking technique is better mockito-inline one or power mockito. what is the difference between them? what do they do behind the scene to achieve this?

codersaty
  • 23
  • 7

0 Answers0