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



mockito-core 版本:1.10.19

电源模拟版本: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());

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

相关内容

  • 没有找到相关文章

最新更新