gpt4 book ai didi

java - 如何模拟 ElasticSearch 客户端

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:33 25 4
gpt4 key购买 nike

我正在努力模拟以下代码:

Client client = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

我的方法:

Settings.Builder settingsBuilder = mock(Settings.Builder.class);
when(settingsBuilder.put(new String("test"), new String("test"))).thenReturn(settings.settingsBuilder());
when(settingsBuilder.build()).thenReturn(settings);

TransportClient.Builder clientBuilder = mock(TransportClient.Builder.class);
when(clientBuilder.settings(settings)).thenReturn(clientBuilder);

到目前为止,测试工作正常,但当尝试模拟客户端上使用的其他类时,Mockito 会抛出以下异常:

错误:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

问题:

现在,我知道这可能会被抛出,因为我没有正确地 mock 某些东西,但我不知道这次我的 mock 出了什么问题。如何正确模拟客户端,以便模拟所有依赖类并返回新的模拟客户端?

谢谢。

最佳答案

我将根据您的类(class)名称进行一些猜测。

Client client = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

假设 TransportClient.builder() 返回 TransportClient.Builder,那么您需要:

when(clientBuilder.settings(anyOf(Settings.class)).thenReturn(clientBuilder);
when(clientBuilder.build()).thenReturn(a transport client mock);

我假设 TransportClient.addTransportAddress 不需要模拟 - 它只需要验证。

关于java - 如何模拟 ElasticSearch 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36876476/

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