我有 3 节课:
public class SomeDAO {
// that method I'd want to catch and change
public void getObj() { ... }
}
public class MainService {
private Service2 service2;
public void doMain() {
service2.doSomethingAnother();
}
}
public class Service2 {
private SomeDAO someDAO
public void doSomethingAnother() {
someDAO.getObj();
}
}
我所需要的 - 调用doMain但在 service2.doSomethingAnother() 中使用自定义someDao.getObj ( ):
public TestClass {
@InjectMocks
private final MainService mainService = new MainService();
@InjectMocks
private final Service2 service2 = new Service2();
@Mock
private SomeDAO someDao;
@Test
public void testMe() {
// substitution
when(someDao.getObj()).thenReturn(new MyObj());
// then I'm calling the outer method
mainService.doMain();
}
}
运行该测试时,我在mainService.doMain()中有 NPE :service2 in null..
testMe对象的内部service2是活动的而不是 null,它已被声明为类变量并被初始化。
我是否误解了@InjectMock 的行为?