即使我遵循了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
    }
}

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

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

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

最佳答案

我基本上只是输入了您在这里得到的信息,对我来说一切正常。

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

    }
}

10-04 21:44