0

我想模拟开玩笑的客户,这样我就可以测试了

@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?

4

1 回答 1

1

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

when(mockJestClient.execute(ArgumentMatchers.any(Search.class))).thenThrow(IOException.class);
于 2017-03-07T21:17:27.430 回答