gpt4 book ai didi

java - 使用mockito captor捕获发送到方法的参数

转载 作者:行者123 更新时间:2023-12-02 06:00:20 24 4
gpt4 key购买 nike

我想在客户端提交消息时捕获 CustomMessageConverter 类的 readInternal() 中的参数 inputMessage。这里的客户端对象不是模拟对象。

@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...
}
...
}

在 AbstractHttpMessageConverter 类中:

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

所以,我编写了一个mockito类来捕获它。

但是,它仍然会转到常规转换器类。你能建议我做错了什么吗?

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

最佳答案

根据 limitations of Mockito ,您无法 stub 或验证 final 方法。简而言之,由于该方法被标记为final,因此Java会跳过在方法表中查找该方法(或调用Mockito创建的Proxy对象)并直接在对方法实现的调用中进行编译。通过直接编译的调用,Mockito 没有机会用自己的答案替换 stub 或调用跟踪逻辑以进行验证。

尝试模拟 readInternal,或者重构代码以依赖接口(interface)而不是实现。 Mockito 可以模拟接口(interface)上的任何方法,因为接口(interface)内不允许存在最终性或可见性问题。

关于java - 使用mockito captor捕获发送到方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22724946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com