我有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();
}
}
Run Code Online (Sandbox Code Playgroud)
我所需要的-调用doMain时而是使用自定义someDao.getObj()内service2.doSomethingAnother() :
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();
}
}
Run Code Online (Sandbox Code Playgroud)
运行该测试时,我在mainService.doMain()中的 NPE :null2中的service2.
在testMe对象中,service2是活动的而不是null,它已被声明为类变量并被初始化.
我是否误解@InjectMock行为?
Service2没有注入MainService,因为它不是模拟.因此,对象的server2属性mainService是null.
你也试图嘲笑太深.测试的正确方法MainService是模拟依赖性Service2而不是SomeDAO.
Service2在模拟依赖项的地方,可以更好地使用单独的测试类SomeDAO.
public TestClass {
@InjectMocks
private MainService mainService;
@Mock
private Service2 service2;
@Before
public void setUp() {
initMocks(this);
}
@Test
public void testMe() {
mainService.doMain();
verify(service2).doSomethingAnother();
}
}
Run Code Online (Sandbox Code Playgroud)