被注入对象要调用私有方法,加了@PrepareForTest注解,还要往被注入的对象注入别的mock类,此时用@InjectMocks和@Mock,然后直接doReturn会报java.lang.NullPointerException异常,需要手动将其注入。
@RunWith(PowerMockRunner.class)
@PrepareForTest({Parents .class, Child.class})
public class Test {
@InjectMocks
private Parents parents;
@Mock
private Child child;
@Test
public void test(){
//手动将child注入到parents中
ReflectionTestUtils.setField(parents, "child", child);
doNothing().when(child.cexecute(any(),any()));
//可以在这里spy parents,然后调用parents的私有方法
int a = parents.pexecute(0);
Assert.assertNull(a);
}
}