简体   繁体   English

如何模拟 JestClient、elasticSearch

[英]How to mock JestClient, elasticSearch

I want to mock jest client so I can test我想模拟笑话客户端,以便我可以测试

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

I want to mock jest so it throws the IOException and do some other testing, I have tried mocking like this:我想嘲笑 jest 所以它抛出 IOException 并做一些其他测试,我试过这样嘲笑:

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

    elasticsearchPersonRepository = new ElasticsearchPersonRepository(mockJestClient);

to no avail, when I call the test无济于事,当我调用测试时

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

    elasticsearchPersonRepository.findAll();

}

it throws null pointer exception instead of IOExcept.它抛出空指针异常而不是 IOExcept。 what am I doing wrong?我究竟做错了什么? how do I mock the JestClient?我如何模拟 JestClient?

You should use neither 'search' nor 'null' but special 'any' argument for execute.您不应该使用 'search' 或 'null',而是使用特殊的 'any' 参数来执行。 If it is Mockito (other mock frameworks have simular functionality)如果是 Mockito(其他模拟框架也有类似功能)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM