dtech
dtech

Reputation: 14060

Mocking static class with powermockito

Even though I followed the manual I cannot seem to mock a static method with PowerMock. I'm trying to mock a singleton god class.

The test code is as follows:

@RunWith(PowerMockRunner.class)
@PrepareForTest(GodClass.class)
public class SomeTestCases {
    @Test
    public void someTest() {
         PowerMockito.mockStatic(GodClass.class);
         GodClass mockGod = mock(GodClass.class);
         when(GodClass.getInstance()).thenReturn(mockGod);
         // Some more things mostly like:
         when(mockGod.getSomethingElse()).thenReturn(mockSE);

         // Also tried: but doesn't work either
         // when(GodClass.getInstance().getSomethingElse()).thenReturn(mockSE);

         Testee testee = new Testee(); // Class under test
    }
}

And Testee:

class Testee {
     public Testee() {
    GodClass instance = GodClass.getInstance();
    Compoment comp = instance.getSomethingElse();
     }
}

However, this doesn't working. Debugging mode shows that instance is null. What must be done different?

(Yes, I know the code is horrible but it's legacy and we want to have some unit tests before refactoring)

Upvotes: 3

Views: 1740

Answers (1)

Mike B
Mike B

Reputation: 5451

I just entered basically what you've got here and it's working fine for me.

public class GodClass
{
    private static final GodClass INSTANCE = new GodClass();

    private GodClass() {}

    public static GodClass getInstance()
    {
        return INSTANCE;
    }

    public String sayHi()
    {
        return "Hi!";
    }
}

public class Testee
{
    private GodClass gc;
    public Testee() {
        gc = GodClass.getInstance();
    }

    public String saySomething()
    {
        return gc.sayHi();
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(GodClass.class)
public class GodClassTester
{
    @Test
    public void testThis()
    {
        PowerMockito.mockStatic(GodClass.class);
        GodClass mockGod = PowerMockito.mock(GodClass.class);
        PowerMockito.when(mockGod.sayHi()).thenReturn("Hi!");
        PowerMockito.when(GodClass.getInstance()).thenReturn(mockGod);

        Testee testee = new Testee();
        assertEquals("Hi!", testee.saySomething());

    }
}

Upvotes: 2

Related Questions