使用powermockito模拟静态类

时间:2014-01-10 15:43:45

标签: java unit-testing mocking powermock

即使我跟着manual,我也似乎无法使用PowerMock模拟静态方法。我正试图嘲笑一个单身人士的上帝阶级。

测试代码如下:

@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
    }
}

和受托人:

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

然而,这不起作用。调试模式显示instancenull。必须做些什么不同?

(是的,我知道代码很糟糕,但它是遗留的,我们希望在重构之前进行一些单元测试)

1 个答案:

答案 0 :(得分:2)

我刚刚输入了你在这里的内容,它对我来说很好。

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

    }
}