简体   繁体   English

Easymock对象数组匹配器

[英]Easymock matcher for Object Array

I have the following class: 我有以下课程:

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);

}

} }

My test method: 我的测试方法:

   @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);

}

When i run this test class, i get Assertion error for Unexpected method call. 当我运行此测试类时,出现意外的方法调用断言错误。 Its expected because in the test class, the UserDetailTO instance inserted in the array will not match with the instance created in the Listener class. 符合预期,因为在测试类中,插入到数组中的UserDetailTO实例与在Listener类中创建的实例不匹配。

But then, how to resolve this problem? 但是,如何解决这个问题呢?

It looks like a problem with UserDetailTO.equals(Object) method. 看来UserDetailTO.equals(Object)方法有问题。 Are 2 UserDetailTO objects equal if they have the same user id and null 2nd parameter? 如果两个UserDetailTO对象具有相同的用户ID和空的第二个参数,它们是否相等?

Also your line EasyMock.expectLastCall(); 您的行EasyMock.expectLastCall(); isn't needed. 不需要。 When a mock is in replay mode, all void methods are automatically "expected". 当模拟处于重播模式时,所有void方法都会自动“预期”。 You only need to call EasyMock.expectLastCall() if you want to perform some other behavior like throw an exception or invoke an IAnswer when that void method is called. 如果要执行其他一些行为(例如引发异常或在调用该void方法时调用IAnswer EasyMock.expectLastCall()则只需调用EasyMock.expectLastCall()

For example if you wanted the sendEmail method to throw an Exception: 例如,如果您想让sendEmail方法抛出一个异常:

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

EasyMock.replay(handlerMock);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM