我目前正在使用今年春季mvc应用程序中的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(“任务已完成”)方法!
答案 0 :(得分:1)
声明
verify(mockGf).makeCustomGUI("test");
您是否尝试验证是否已使用参数“test”调用“makeCustomerGUI”。如果这是你的要求,你可以这样做:
GUIFactory mockGf = mock(GUIFactory.class);
mockGf.makeCustomerGUI("test");
verify(mockGf).makeCustomGUI("test");
创建模拟对象后,Mockito将记住其上的所有调用。因此,您可以有选择地验证调用。