使用PowerMock嘲讽模拟静态方法仅适用于首次测试,不适用于所有测试

时间:2019-07-11 11:21:09

标签: java mockito powermock powermockito

被测类“类A”具有类型为“ B nonStaticField”的非静态字段,该字段通过调用“类B”的静态方法getValue(int i)实例化。我正在嘲笑此类B.getValue(),因此它为我返回了该nonStaticField的嘲笑。但是我注意到:

when(B.getValue()).thenReturn(mockOfNonStaticField)仅针对第一个测试方法正确返回了模拟,在以下所有情况下,返回的不是模拟。

class A{

private B nonStaticField = B.getValue(someInt); // static method

}


@RunWith(PowerMockRunner.class)
@PrepareForTest({B.class})
class ATest{

@Mock
private static B nonStaticFieled; // it's static here, non-static in class under test

@BeforeClass
    public static void initStatic() {
        mockStatic(B.class);
        nonStaticFieled = mock(B.class); // hence it has to be static
        when(B.getValue(any(Integer.class))).thenReturn(nonStaticFieled);
    }

@Test
public void testOne(){
// here mocknig works, when class under test (A) is instantiated mock is returned from B.getValue()
}

@Test
public void testTwo(){
// here mocknig does not work, no mock is returned thus I can't verify this mock interactions by calling verify(nonStaticField).someMethod();
}


}

我想要的很简单-我希望每次测试都返回此nonStaticField模拟。

0 个答案:

没有答案