需要帮助决定需要采取什么方法来测试下面的代码
我有一个名为
的方法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;
}
我的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);
}
问题来自行
response = constructResponse(errorCode, errorDesc);
它在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)
让我知道我应该采取什么方法。 谢谢。
答案 0 :(得分:5)
答案 1 :(得分:1)
我找到了这样做的方法。 您需要实现接口org.easymock.IArgumentMatcher
public class ObjectEquals implements IArgumentMatcher {
/** The expected. */
private Object expected;
/**
* Instantiates a new criterion equals.
*
* @param expected
* the expected
*/
public ObjectEquals(final Object expected) {
this.expected = expected;
}
/* (non-Javadoc)
* @see org.easymock.IArgumentMatcher#matches(java.lang.Object)
*/
public boolean matches(final Object actual) {
return expected.getClass().equals(actual.getClass());
}
/* (non-Javadoc)
* @see org.easymock.IArgumentMatcher#appendTo(java.lang.StringBuffer)
*/
public void appendTo(final StringBuffer buffer) {
buffer.append("buffer(");
}
}
并在您的测试类中添加方法
/*
* Eq criterion.
*
* @param criterion the criterion
*
* @return the criterion
*/
public static <T> T eqCriterion(final Class<T> className, Object object) {
EasyMock.reportMatcher(new ObjectEquals(object));
return null;
}
现在转到easymock时使用方法eqCriterion
EasyMock.expect(messageDAOInf.convertMessagesAsAppropriate(
response)).andReturn(response);
简而言之,用
代替上面一行EasyMock.expect(messageDAOInf.convertMessagesAsAppropriate(
eqCriterion(Response.class, response))).andReturn(response);
这样它就会使用这个模拟的响应实例而不是实际代码生成的响应实例。