即使我遵循了手册,我似乎也无法用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();
}
}
但是,这不起作用。调试模式显示instance
null
。必须采取哪些不同的做法?
我知道代码很糟糕,但它是遗留的,我们希望在重构之前进行一些单元测试)
我刚刚输入了您在这里的基本内容,它对我来说工作正常。
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());
}
}