验证重载的方法调用

时间:2013-03-29 14:42:37

标签: java mockito

我正在尝试使用Mockito verify功能验证方法被多次调用。然而,我遇到的问题是该方法被重载,因此声称该方法未被调用。要在混合中添加扳手,我还希望捕获传递给此方法的参数。以下是我到目前为止的情况:

@Test
public void simpleTest() throws IOException {
    FlumeAppender mockAppender = Mockito.mock(FlumeAppender.class);
    ArgumentCaptor<LoggingEvent> arguments = ArgumentCaptor.forClass(LoggingEvent.class);

    // Load the message that should be sent to the class being tested
    InputStream in = this.getClass().getResourceAsStream("/testMessage.xml");
    StringWriter writer = new StringWriter();
    IOUtils.copy(in, writer, "UTF-8");
    String testMessage = writer.toString();

    // Send a message to the class being tested. This class will 
    // (hopefully) call the function I am listening to below
    eventSubscriber.handleMessage(testMessage);

    // Verify that the append method was called twice
    Mockito.verify(mockAppender, Mockito.times(2)).append(
            arguments.capture());

    // Do something with the arguments
}

就像我说的那样,我试图验证(附加)的函数被重载了。是否有可能在仍然捕获参数时指定我要求验证的附加函数?

1 个答案:

答案 0 :(得分:0)

令人尴尬的是,我发现我的问题的解决方案是一个简单错误的结果。我将发布答案以供参考。

创建ArgumentCaptor时,请使用泛型指定您期望的参数类型。我已经这样做了,但遗憾的是我使用了我不希望被调用的方法的其他版本之一的类型。简单的错误。

// This declaration
ArgumentCaptor<LoggingEvent> arguments = ArgumentCaptor.forClass(LoggingEvent.class);

// Should have been:
ArgumentCaptor<Event> arguments = ArgumentCaptor.forClass(Event.class);

一旦这是正确的,验证函数应该按预期工作,使用ArgumentCaptor中的类型来确定要查看的方法。

如此接近......

相关问题