我正在努力嘲笑下面的代码:
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.
问题:
现在,我承认这可能会被抛出,因为我没有正确地嘲笑某些东西,但是这次我无法弄清楚我的嘲笑有什么问题。如何正确模拟客户端,以便模拟所有依赖类并返回新的模拟客户端?
感谢。
答案 0 :(得分:0)
根据你的班级名称,我会在这里猜一点。
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,我假设,不需要模拟 - 它只需要验证。