我需要模拟 RestHighLevelClient 来测试我的代码。基本上,当我调用 RestHighLevelClient 的"搜索"方法时,我得到 UnfinishStubbingException 或 WrongTypeOfReturnValue。
PowerMockito.doReturn(searchResponse).when(client.search(searchRequest, RequestOptions.DEFAULT));
此示例引发未完成的存根异常。
PowerMockito.when(client.search(searchRequest, RequestOptions.DEFAULT)).thenReturn(searchResponse);
此示例引发 WrongTypeOfReturnValue。
这是我的配置
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {
RestHighLevelClient.class
...otherClasses
})
我用谷歌搜索了这两个例外,但我没有在"thenReturn"方法中调用"mock.someMethod(("。似乎每种方法都不起作用。
RestHighLevelClient
的访问包装在抽象中。使用与RestHighLevelClient
相同的签名。最后,模拟抽象。例如:
public interface RestHighLevelClientWrapper {
SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException;
}
@Service
public class RestHighLevelClientWrapperImpl implements RestHighLevelClientWrapper {
private final RestHighLevelClient client;
@Autowired
public RestHighLevelClientWrapperImpl(RestHighLevelClient client) {
this.client = client;
}
@Override
public SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException {
return client.search(searchRequest, options);
}
}
这是 elasticsearch 存储库中的一个未解决的问题。我所能做的就是:
@Mock
private RestHighLevelClient restHighLevelClient;
@Before
public void setup() {
restHighLevelClient = mock(RestHighLevelClient.class);
}
然后按如下方式使用它
when(elasticClientHandler.createRestClient())
.thenReturn(restHighLevelClient);
好吧,根据该评论,最好的工作解决方案是创建包装委托服务并模拟它,而不是嘲笑整个RestHighLevelClient
的事情(我确定您没有使用所有当前方法(
可以使用PowerMockito模拟RestHighLevelClient。我们可以像下面这样做。
public class ElasticSearchService{
private RestHighLevelClient client;
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ElasticSearchService.class, RestHighLevelClient.class,OtherClasses.. })
public class ElasticSearchServiceTest {
RestHighLevelClient restHighLevelClient ;
@Before
public void setup() {
esInstance = new ElasticSearchService();
//Mock client here and set it to the instance of class to be tested
restHighLevelClient = PowerMockito.mock(RestHighLevelClient.class);
esInstance.setClient(restHighLevelClient);
}
}