java - 如何模拟 JestClient、elasticSearch

标签 java unit-testing exception mocking elasticsearch-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());
}

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

最佳答案

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

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

关于java - 如何模拟 JestClient、elasticSearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658318/

相关文章:

java - 对所有列独立排序形成二维数组java

java - 将 DataHandler 转换为 byte[]

java - 如何检查 ArrayBlockingQueue 是否被锁定或队列元素当前由线程处理?

c++ - 从保护类析构函数中抛出异常导致 std::terminate

java - (已解决)序列化(写入)充满对象的Arraylist不断抛出 "NotSerializableException"

python - 无法在 Python 中捕获异常 IndexError?

java - JProgressBar 未触发 setProgress 上的 propertyChange

java - 如何自动(通过 UT)检测 REST 合约中缺少的无参数构造函数?

java - 如何对 Maven 多模块 Spring 应用程序进行单元测试?

reactjs - enzyme 和 react 测试库之间的区别