0

我目前在这个 spring 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("Task has been completed") 方法!

4

1 回答 1

1

随着声明

verify(mockGf).makeCustomGUI("test");

您是否正在尝试验证是否已使用参数“test”调用了“makeCustomerGUI”。如果这是您的要求,您可以执行以下操作:

GUIFactory mockGf = mock(GUIFactory.class);
mockGf.makeCustomerGUI("test");
verify(mockGf).makeCustomGUI("test");

创建模拟对象后,Mockito 将记住对其的所有调用。因此,您可以有选择地验证调用。

于 2013-08-29T14:46:53.877 回答