Aaron Aaron - 1 year ago 158
Java Question

How can I mock private static method with PowerMockito?

I'm trying to mock private static method

. See code below

public class Util {
public static String method(){
return anotherMethod();

private static String anotherMethod() {
throw new RuntimeException(); // logic was replaced with exception.

Here is me test code

public class UtilTest extends PowerMockTestCase {

public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception {

PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc");

String retrieved = Util.method();

assertEquals(retrieved, "abc");

But every tile I run it I get this exception

java.lang.AssertionError: expected object to not be null

I suppose that I'm doing something wrong with mocking stuff. Any ideas how can I fix it?

Answer Source

To to this, you can use PowerMockito.spy(...) and PowerMockito.doReturn(...). Moreover, you have to specify the PowerMock runner at your test class, as follows:

public class UtilTest {

   public void testMethod() throws Exception {
      PowerMockito.doReturn("abc").when(Util.class, "anotherMethod");

      String retrieved = Util.method();

      Assert.assertEquals(retrieved, "abc");

Hope it helps you.