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:

        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. what am I doing wrong? how do I mock the JestClient?

Upvotes: 0

Views: 2484

Answers (1)

Andriy Slobodyanyk
Andriy Slobodyanyk

Reputation: 2085

You should use neither 'search' nor 'null' but special 'any' argument for execute. If it is Mockito (other mock frameworks have simular functionality)

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

Upvotes: 1

Related Questions