我知道你不能使用 mockito 来模拟静态方法。但是我试图模拟的方法不是静态的,但它调用了静态方法。那么我可以模拟这个方法吗?
运行测试时出现异常。对静态方法的调用是此异常的原因吗?
要测试的类:
public class MyAction{
public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
MyService service = new MyService();
**form.setList(service.getRecords(searchRequest));**
}
}
模拟类和方法:
public class MyService{
public List getRecords(SearchRequest sr){
List returnList = new ArrayList();
MyDao dao = DAOFactory.getInstance().getDAO();---->Call to static method
// Some codes
return returnList;
}
}
具有静态方法的类:
public class DAOFactory{
private static DAOFactory instance = new DAOFactory();
public static DAOFactory getInstance() {------> The static method
return instance;
}
}
我的测试:
@Test
public void testSearch() throws Exception{
MyService service = mock(MyService.class);
MyAction action = new MyAction();
List<MyList> list = new ArrayList<MyList>();
when(service.getRecords(searchRequest)).thenReturn(list);
ActionForward forward = action.search(mapping, form, request, response);
}
这是我运行测试时的堆栈跟踪。请记住,为简单起见,我更改了类的名称。