You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试无法获取属性:如何从嵌套集合提取名称字符串列表?

解决从嵌套Map列表中提取名称字符串的单元测试问题

问题根源

从调试结果能看出,接口返回的列表元素是LinkedHashMap,但"name"字段对应的不是直接的字符串,而是嵌套的LinkedHashMap(内部键为name,对应值才是你要的名称字符串)。原代码直接调用e.get("name")拿到的是这个嵌套Map,而非目标字符串,导致断言失败。

修正方案

方案1:直接处理嵌套Map

修改流映射逻辑,先取出"name"对应的嵌套Map,再从中提取实际名称:

List<String> names = body.stream()
    .map(e -> (Map<String, String>) e.get("name"))
    .map(nestedMap -> nestedMap.get("name"))
    .collect(Collectors.toList());

方案2:严谨版(避免类型转换异常)

如果担心数据结构不稳定,可以增加类型校验:

List<String> names = body.stream()
    .filter(item -> item.get("name") instanceof Map)
    .map(item -> (Map<?, ?>) item.get("name"))
    .filter(nestedMap -> nestedMap.get("name") instanceof String)
    .map(nestedMap -> (String) nestedMap.get("name"))
    .collect(Collectors.toList());

方案3:优化RestTemplate返回类型(推荐)

用ParameterizedTypeReference指定更精确的返回类型,避免强制类型转换:

// 替换原ResponseEntity的获取逻辑
ResponseEntity<List<Map<String, Map<String, String>>>> response = restTemplate.exchange(
    "http://localhost:5050/finance/rest/contracts",
    HttpMethod.GET,
    null,
    new ParameterizedTypeReference<List<Map<String, Map<String, String>>>>() {}
);
List<Map<String, Map<String, String>>> body = response.getBody();

// 提取名称
List<String> names = body.stream()
    .map(item -> item.get("name").get("name"))
    .collect(Collectors.toList());

验证效果

替换上述任意方案的代码后,重新运行测试,names列表会正确收集到"Jen"、"Nakzo"、"Renes",断言containsInAnyOrder会顺利通过。

内容的提问来源于stack exchange,提问作者jennifer ruurs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 03:07:17