java.lang.AssertionError:意外的方法调用convertMessagesAsAppropriate(com.Response@1bb35b)

Gee*_*pat 3 java easymock

需要帮助决定需要采取什么方法来测试下面的代码

我有一个叫做的方法

private messageDAOInf messageDAO;

public Response verifyUser(Request request) {
    Response response = null;

    if (someCondition) {
        /* -----------Some processing here---------- */
    } else {
        response = constructResponse(errorCode, errorDesc);     
    }

    // Do more processing with messages from response
    response = messageDAOInf
        .convertMessagesAsAppropriate(response);

    return response;
}
Run Code Online (Sandbox Code Playgroud)

我的EasyMock代码就在这里

/** The message dao inf. */
private MessageDAOInf messageDAOInf;

private VerifyUserService verifyUserServiceI;

@Before

public void setUp() throws Exception {
    messageDAOInf = EasyMock.createMock(MessageDAOInf.class);
    verifyUserService = new VerifyUserService();
    verifyUserService.setMessageDAOInf(messageDAOInf);
}

@Test

public void testErrorResponse() {
    Request request = loadRequest();

    Response response = constructErrorResponse();

    EasyMock.expect(messageDAOInf.convertMessagesAsAppropriate(
        response)).andReturn(response);

    EasyMock.replay(messageDAOInf);

    Response response2 = verifyUserService.verifyUser(request);

    assertFailedResponse(response2);
}
Run Code Online (Sandbox Code Playgroud)

问题来自于线路

response = constructResponse(errorCode, errorDesc);     
Run Code Online (Sandbox Code Playgroud)

它在verifyUser方法中构造错误响应并将其传递给 messageDAOInf.convertMessagesAsAppropriate()

但是通过简单的模拟,它会传递一些其他实例(模拟一个),因此会出错

java.lang.AssertionError: 
  Unexpected method call convertMessagesAsAppropriate(***Response@1bb35b***):
    convertMessagesAsAppropriate(***Response@1b5d2b2***): expected: 1, actual: 0
    at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29)
    at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:56)

让我知道我应该采取什么方法.谢谢.

Doc*_*uss 5

您最初的代码预计convertMessagesAsAppropriate将有确切的被称为实例Response,你在测试中创造了:显然不会那么做的.

您所做的更正与使用EasyMock.anyObject()允许任何Response实例的内置方法基本相同.如果您想要检查单元测试,那很好.或者,您可以向您添加额外的逻辑,ArgumentMatcher以证明Response作为参数传递的逻辑确实是ErrorResponse,或Capture响应并在您的测试中检查它.这一切都取决于您的测试水平:-)