无法完全模拟 RestHighLevelClient

Not able to fully mock RestHighLevelClient

我需要模拟 RestHighLevelClient 来测试我的代码。基本上当我调用 RestHighLevelClient 的 "search" 方法时,我得到 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()"。似乎每种方法都不起作用。

它是 elasticsearch 存储库中的一个开放 issue。我所能做的就是:

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

然后按如下方式使用它

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

好吧,根据那个 comment 最好的解决方案是创建包装委托服务并模拟它而不是模拟整个 RestHighLevelClient 事情(我确定你没有使用所有目前的方法)

可以使用 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);
}

}

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

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);
    }
}