无法完全模拟RestHighLevelClient

时间:2019-06-11 15:31:11

标签: java elasticsearch mockito powermockito

我需要模拟RestHighLevelClient来测试我的代码。基本上,当我调用RestHighLevelClient的“搜索”方法时,我会得到UnfinishedStubbingException或WrongTypeOfReturnValue。

PowerMockito.doReturn(searchResponse).when(client.search(searchRequest, RequestOptions.DEFAULT));

此示例引发UnfinishedStubbingException。

PowerMockito.when(client.search(searchRequest, RequestOptions.DEFAULT)).thenReturn(searchResponse);

此示例抛出WrongTypeOfReturnValue。

这是我的配置

@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {
        RestHighLevelClient.class
...otherClasses
})

我用谷歌搜索了两个异常,但是我没有在“ thenReturn”方法中调用“ mock.someMethod()”。似乎每种方法都行不通。

4 个答案:

答案 0 :(得分:0)

这是Elasticsearch存储库中的开放issue。我所能做的是以下事情:

@Mock
private RestHighLevelClient restHighLevelClient;
 @Before
public void setup() {
   restHighLevelClient = mock(RestHighLevelClient.class);
}

然后按照以下说明使用它

        when(elasticClientHandler.createRestClient()).thenReturn(restHighLevelClient);

答案 1 :(得分:0)

嗯,根据comment,最好的解决方案是创建包装委托服务并对其进行模拟,而不是模拟整个RestHighLevelClient(我确定您没有使用所有现有方法) )

答案 2 :(得分:0)

可以使用 PowerMockito 模拟 RestHighLevelClient。我们可以这样做。

public class ElasticSearchService{

    private RestHighLevelClient client;

}


@RunWith(PowerMockRunner.class)
@PrepareForTest({ ElasticSearchService.class, RestHighLevelClient.class,OtherClasses.. })
public class ElasticSearchServiceTest {
    RestHighLevelClient restHighLevelClient ;

@Before
    public void setup() {
        esInstance = new ElasticSearchService();
       
//Mock client here and set it to the instance of class to be tested
        restHighLevelClient = PowerMockito.mock(RestHighLevelClient.class);
        esInstance.setClient(restHighLevelClient);
}

}

答案 3 :(得分:0)

在抽象中包装对 RestHighLevelClient 的访问。使用与 RestHighLevelClient 相同的签名。最后,mock 抽象。例如:

public interface RestHighLevelClientWrapper {
    SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException;
}
@Service
public class RestHighLevelClientWrapperImpl implements RestHighLevelClientWrapper {

    private final RestHighLevelClient client;

    @Autowired
    public RestHighLevelClientWrapperImpl(RestHighLevelClient client) {
        this.client = client;
    }

    @Override
    public SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException {
        return client.search(searchRequest, options);
    }
}

```