gpt4 book ai didi

java - 如何模拟 JestClient、elasticSearch

转载 作者:行者123 更新时间:2023-12-02 13:42:35 25 4
gpt4 key购买 nike

我想模拟笑话客户端,以便我可以测试

@Override
public List<Person> findAll() {
SearchResult result = null;
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(personIndexName)
.addType(personTypeName).build();
try {
result = client.execute(search);
if (!result.isSucceeded()) {
return null;
}

} catch (IOException e) {
logger.error("The search can't be completed " + e.getMessage());
}
List<SearchResult.Hit<Person, Void>> hits = result.getHits(Person.class);
return hits.stream().map(this::getPerson).collect(Collectors.toList());
}

我想模拟笑话,所以它会抛出 IOException 并进行一些其他测试,我尝试过这样的模拟:

        when(mockJestClient.execute(search)).thenThrow(IOException.class);
when(mockJestClient.execute(null)).thenThrow(IOException.class);

elasticsearchPersonRepository = new ElasticsearchPersonRepository(mockJestClient);

当我调用测试时却无济于事

  @Test(expected = IOException.class)
public void findAll() throws Exception {

elasticsearchPersonRepository.findAll();

}

它抛出空指针异常而不是IOExcept。我究竟做错了什么?我如何模拟 JestClient?

最佳答案

您不应使用“search”或“null”,而应使用特殊的“any”参数来执行。如果是Mockito(其他mock框架也有类似的功能)

when(mockJestClient.execute(ArgumentMatchers.any(Search.class))).thenThrow(IOException.class);

关于java - 如何模拟 JestClient、elasticSearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658318/

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