如何模拟JestClient,elasticSearch

时间:2017-03-07 21:05:17

标签: java unit-testing exception-handling mocking jest

我想模仿jest客户端,所以我可以测试

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

我想模拟jest,所以它抛出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?

1 个答案:

答案 0 :(得分:1)

你不应该使用&#39;搜索&#39;也不是&#39; null&#39;但特别的&#39;任何&#39;执行的参数。如果它是Mockito(其他模拟框架具有类似的功能)

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