我想模拟开玩笑的客户,这样我就可以测试了
@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?