简体   繁体   English

使用mockito captor捕获发送给方法的参数

[英]Using mockito captor to capture the argument sent to a method

I would like to capture the argument inputMessage in the readInternal() of the CustomMessageConverter class when client submits a message. 我想在客户端提交消息时捕获CustomMessageConverter类的readInternal()中的参数inputMessage。 client object here is not a mock object. 这里的客户端对象不是模拟对象。

@Component
public class CustomMessageConverter extends AbstractHttpMessageConverter<Object> {

...

    @Override
    protected Object readInternal(final Class<? extends Object> clazz, final HttpInputMessage inputMessage) throws IOException,
            HttpMessageNotReadableException {

            ...do something here...
    }
...
}

In AbstractHttpMessageConverter class: 在AbstractHttpMessageConverter类中:

@Override
public final T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException {
    return readInternal(clazz, inputMessage);
}

So, I wrote a mockito class to capture it. 所以,我写了一个mockito类来捕捉它。

But, it is still going to the regular converter class. 但是,它仍然是常规转换器类。 Could you suggest what I am doing wrong? 你能说一下我做错了什么吗?

@Mock
CustomMessageConverter mockMessageConverter;

@Captor
private ArgumentCaptor<HttpInputMessage> inputMessage;


@Test
public void test() {
    when(mockMessageConverter.read(CustomMessage.class, inputMessage.capture())).thenReturn(null);
    client.submitMessage(Message);
    verify(mockMessageConverter, times(1));
    Object actual = customConverter.read(CustomMessage.class, inputMessage.getValue());
}

Per the limitations of Mockito , you can't stub or verify final methods. 根据Mockito限制 ,您不能存根或验证final方法。 In short, because the method is marked final, Java skips looking up the method in a method table (or calling the Proxy object that Mockito creates) and compiles in a call to the method implementation directly. 简而言之,因为该方法被标记为final,所以Java跳过在方法表中查找方法(或调用Mockito创建的Proxy对象)并直接编译方法实现。 With that direct-compiled call there is no opportunity for Mockito to substitute its own answers for stubbing or call-tracking logic for verification. 通过这种直接编译的呼叫,Mockito没有机会用自己的答案替换存根或呼叫跟踪逻辑进行验证。

Try mocking readInternal instead, or refactor your code to rely on an interface instead of an implementation. 尝试readInternal ,或者重构代码以依赖接口而不是实现。 Mockito can mock any method on an interface, because there are no finality or visibility problems allowed within interfaces. Mockito可以模拟接口上的任何方法,因为接口中不允许存在终结性或可见性问题。

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

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