为什么mockStatic没有按预期运行?

时间:2017-02-09 10:12:24

标签: java unit-testing junit mockito powermock

mockito-core版本: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());
    }
}

非常感谢。

1 个答案:

答案 0 :(得分:1)

您正在模拟静态类,这意味着如果您没有明确定义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()