Object Array的Easymock匹配器

时间:2013-10-10 13:03:52

标签: java junit mocking easymock

我有以下课程:

public class Listener{

@Autowired
private Handler handler;


public void receiveMessage(Message<String> message) {
    String xmlMessage = message.getPayload().toString();

    XStream xstream = new XStream();
    xstream.processAnnotations(InfoTO.class);

    infoTO = (InfoTO) xstream.fromXML(xmlMessage);


    UserDetailTO[] userDetailTO = { new UserDetailTO(infoTO.getUserId(), null) };
    handler.sendEmail(userDetailTO);

}

}

我的测试方法:

   @Test
public void testRecieve() {
    UserDetailTO[] userDetails={new UserDetailTO("zzzz",null)};

    Handler handlerMock=EasyMock.createMock(Handler.class);
    handlerMock.sendEmail(aryEq(userDetails));
    EasyMock.expectLastCall();
    EasyMock.replay(handlerMock);
    ReflectionTestUtils.setField(listener, "handler", handlerMock);

    String message = "Test Payload";
    Message<String> finalMessage = MessageBuilder.withPayload(message).build();
    listener.receiveMessage(finalMessage);

}

当我运行此测试类时,我收到意外方法调用的Assertion错误。它的预期是因为在测试类中,插入到数组中的UserDetailTO实例将与Listener类中创建的实例不匹配。

但是,如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

UserDetailTO.equals(Object)方法看起来很像问题。如果2 UserDetailTO个对象具有相同的用户ID且为空第二个参数,那么它们是否相等?

此外,您的行EasyMock.expectLastCall();也不需要。当mock处于重放模式时,所有void方法都会自动“预期”。如果要执行某些其他行为(如抛出异常或调用该void方法时调用EasyMock.expectLastCall()),则只需调用IAnswer

例如,如果您希望sendEmail方法抛出异常:

Exception expectedException = new Exception(...);
...
handlerMock.sendEmail(aryEq(userDetails));
EasyMock.expectLastCall().andThrow(expectedException);

EasyMock.replay(handlerMock);