要测试的类:IndexController.java
代码:
@Mock
private TemplateWrapper templateWrapper = spy(new TemplateWrapper());
@InjectMocks
private IndexController controller;
verify(templateWrapper).process();
报错:
Wanted but not invoked:
templateWrapper.process();
-> at com.suning.ebuy.cms.web.controller.IndexControllerTest.testIndexSuccess(IndexControllerTest.java:199)
Actually, there were zero interactions with this mock.
错误原因:没有把templateWrapper注入到IndexController.java类中.
解决方法:
1.把templateWrapper注入到IndexController.java类中
controller.setMyObj(templateWrapper); //it is good to have in @before method
2.或者创建templateWrapper的实例类,再执行verify(templateWrapper).process();
templateWrapper = new TemplateWrapper();
verify(templateWrapper).process();