模拟核心版本:1.10.19

powermock版本:1.6.6

我尝试模拟一些静态方法,但输出使我感到困惑。
这是我的代码:

class ClassWithStatics {
    public static int getNextInt() {
        return getInt() + 1;
    }

    public static int getInt() {
        return 1;
    }

    public static long getTime() {
        return System.currentTimeMillis();
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassWithStatics.class, System.class})
public class StubJustOneStatic {
    @Test
    public void test() {
        PowerMockito.mockStatic(ClassWithStatics.class);
        Mockito.when(ClassWithStatics.getInt()).thenReturn(0);

        PowerMockito.mockStatic(System.class);
        Mockito.when(System.currentTimeMillis()).thenReturn(12345L);

        System.out.println("Next Int: " + ClassWithStatics.getNextInt());
        System.out.println("Int: " + ClassWithStatics.getInt());
        System.out.println("Time:" + ClassWithStatics.getTime());
    }
}


输出是

Next Int: 0
Int: 0
Time:0


但是,当我使用以下代码时,ClassWithStatics.getTime()完全打印我想要的内容。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassWithStatics.class, System.class})
public class StubJustOneStatic {
    @Test
    public void test() {
         //  PowerMockito.mockStatic(ClassWithStatics.class);
         //  Mockito.when(ClassWithStatics.getInt()).thenReturn(0);

        PowerMockito.mockStatic(System.class);
        Mockito.when(System.currentTimeMillis()).thenReturn(12345L);

        //  System.out.println("Next Int: " + ClassWithStatics.getNextInt());
        //  System.out.println("Int: " + ClassWithStatics.getInt());
        System.out.println("Time:" + ClassWithStatics.getTime());
    }
}


非常感谢。

最佳答案

您在嘲笑静态类,这意味着,如果未明确定义when().. then()行为,则Mockito将返回默认值(如果为long,则返回0)。

您必须使用间谍程序才能仅模拟某些方法,并让其他方法按实现方式运行:

PowerMockito.spy(ClassWithStatics.class);
Mockito.when(ClassWithStatics.getInt()).thenReturn(5);


现在,当您调用时:

PowerMockito.mockStatic(System.class);
Mockito.when(System.currentTimeMillis()).thenReturn(12345L);

System.out.println("Time:" + ClassWithStatics.getTime());


调用5时应获得ClassWithStatics.getInt(),调用12345L时应获得ClassWithStatics.getTime()

10-07 22:06