繁体   English   中英

使用powermockito模拟静态类

[英]Mocking static class with powermockito

即使我按照手册,我似乎无法使用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 必须做些什么不同?

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

我刚刚进入了你所拥有的东西,它对我来说很好。

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

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM