今日写elastic search 第三方组件相关的单元测试遇到了比较大麻烦,也花了很长时间通过单元测试与代码覆盖率指标。博主测试框架用的是mockito,难点在于需要屏蔽第三方依赖自己构造ES的返回SearchResponse 对象,直接用json赋值SearchResponse 是走不通的,只能通过内部API来赋值创建。废话不多说,直接上干货
- 使用ES REST API获取你要封装的Response对象,注意后面typed_keys是必须的,否则无法解析拿到的json。(至于原因,请移步官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html#/return-agg-type)
https://xxx:xx/index_name/_search?typed_keys
- 解析JSON
// 步骤1得到的json
String json= "{"a":2}";
SearchResponse searchResponse2 =
SearchResponse.fromXContent(new JsonXContentParser(getDefaultNamedXContentRegistry(),
null, new JsonFactory().createParser(json)));
private List<NamedXContentRegistry.Entry> getDefaultNamedXContents() {
// 解析es返回的字段,其中不需要的可以自行删除
Map<String, ContextParser<Object, ? extends Aggregation>> map = new HashMap<>();
map.put("cardinality", (p, c) -> ParsedCardinality.fromXContent(p, (String) c));
map.put("hdr_percentiles", (p, c) -> ParsedHDRPercentiles.fromXContent(p, (String) c));
map.put("hdr_percentile_ranks", (p, c) -> ParsedHDRPercentileRanks.fromXContent(p, (String) c));
map.put("tdigest_percentiles", (p, c) -> ParsedTDigestPercentiles.fromXContent(p, (String) c));
map.put("tdigest_percentile_ranks", (p, c) -> ParsedTDigestPercentileRanks.fromXContent(p, (String) c));
map.put("percentiles_bucket", (p, c) -> ParsedPercentilesBucket.fromXContent(p, (String) c));
map.put("min", (p, c) -> ParsedMin.fromXContent(p, (String) c));
map.put("max", (p, c) -> ParsedMax.fromXContent(p, (String) c));
map.put("sum", (p, c) -> ParsedSum.fromXContent(p, (String) c)