mock有效果的 关键在于
将需要mock的 new 对象所在的被测类添加至@PrepareForTest注解中
@RunWith(PowerMockRunner.class)
@PrepareForTest({TestA.class})
public class TestA {
@Mock
private MyThread myThread;
@Test
private void testSomeMethod() throws Exception {
//mock code......
PowerMockito.whenNew(MyThread.class).withAnyArguments().thenReturn(myThread);
//Assert......
}
}
@PrepareForTest 注解的使用场景:
- 当使用PowerMockito.whenNew方法时,注解@PrepareForTest里写的类是需要mock的new对象代码所在的类
- 当需要mock final 方法的时候,注解@PrepareForTest里写 final 方法所在类
- 当需要mock private 方法的时候,注解@PrepareForTest里写 private 方法所在类
- 当需要mock static 方法的时候,注解@PrepareForTest里写 static 方法所在类