我目前正在这个springmvc应用程序中使用mockito 1.8.4。这是我试图测试的类/方法的代码。
public class CompleteTaskController implements IController {
public static Logger log = Logger.getLogger(CompleteTaskController.class);
@Override
public void handle() {
GUIFactory gf = new GUIFactory();
IDatabasePullListOfUsers pull = new OraclePullListOfUsers();
IDatabaseUserManagement manage = OracleUserManagement.getInstance();
gf.makeGUI("completeTask", pull.pullAssignedRequests(GUIFactory.userLoggedIn));
manage.completeTask(gf.getRequestID(), GUIFactory.userLoggedIn);
gf.makeCustomGUI("Task has been completed");
log.fatal(GUIFactory.userLoggedIn + " has completed the task of request id " + gf.getRequestID());
gf.makeGUI("adminpanel");
}
}
到目前为止,所有的测试都通过了,但最后一次——我似乎不明白为什么。这是我的测试代码:
public class CompleteTaskControllerTest {
@Test
public void testHandleCallsMakeGUIAndPassesItPullAssignedRequestsAndAString(){
CompleteTaskController mockCtc = mock(CompleteTaskController.class);
GUIFactory mockGf = mock(GUIFactory.class);
IDatabasePullListOfUsers mockPull = mock(OraclePullListOfUsers.class);
mockCtc.handle();
verify(mockGf).makeGUI("test", mockPull.pullAssignedRequests("test"));
}
@Test
public void testHandleCallsCompleteTaskAndPassesItGetRequestIDAndAString(){
CompleteTaskController mockCtc = mock(CompleteTaskController.class);
IDatabaseUserManagement mockManage = mock(OracleUserManagement.class);
GUIFactory mockGf = mock(GUIFactory.class);
mockCtc.handle();
when(mockGf.getRequestID()).thenReturn(1);
verify(mockManage).completeTask(mockGf.getRequestID(),"Test");
}
@Test
public void testHandleCallsMakeCustomGUIAndPassesItAString(){
CompleteTaskController mockCtc = mock(CompleteTaskController.class);
GUIFactory mockGf = mock(GUIFactory.class);
mockCtc.handle();
verify(mockGf).makeCustomGUI("test");
}
}
很抱歉把所有这些代码都扔给你-我唯一遇到问题的测试是第三个测试-它试图模拟gf.makeCustomGUI("任务已经完成")方法!
使用语句
verify(mockGf).makeCustomGUI("test");
您是否试图验证是否已使用参数"test"调用了"makeCustomerGUI"。如果这是你的要求,你可以按照以下方式进行:
GUIFactory mockGf = mock(GUIFactory.class);
mockGf.makeCustomerGUI("test");
verify(mockGf).makeCustomGUI("test");
一旦创建了mock对象,Mockito就会记住对它的所有调用。因此,您可以选择性地验证调用。