如何使用AssertJ验证两个HashMap列表的多键对应值一致性
验证两个List<Map<String, String>>中多键取值一致性的实现方法
我有两个List<Map<String, String>>类型的列表,需要验证指定的多个键对应的取值是否一致。现有测试代码示例如下:
List<Map<String, String>> listMap1 = new ArrayList<>(); Map<String, String> map1 = new HashMap<>(); map1.put("Car", "Toyota"); map1.put("Bike", "BMW"); map1.put("ElectricCar", "Tesla"); listMap1.add(map1); System.out.println(listMap1); List<Map<String, String>> listMap2 = new ArrayList<>(); Map<String, String> map2 = new HashMap<>(); map2.put("Car", "Toyota"); map2.put("MotorBike", "TVS"); map2.put("ElectricCar", "Tesla"); listMap2.add(map2); System.out.println(listMap2);
目前已实现单键值的验证方式:
SoftAssertions.assertSoftly(softAssertions -> softAssertions.assertThat(listMap2) .extracting("Car") .contains(listMap1.stream().map(m -> m.get("Car")).toArray()));
多键验证的实现方案
方案1:利用AssertJ的多参数extracting方法
AssertJ的extracting支持传入多个键名,返回包含对应键值的Tuple对象,直接对比两个列表的提取结果即可:
import org.assertj.core.api.SoftAssertions; import org.assertj.core.groups.Tuple; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; // 定义需要验证的目标键集合 List<String> targetKeys = Arrays.asList("Car", "ElectricCar"); SoftAssertions.assertSoftly(softAssertions -> { // 从listMap1中提取指定键的Tuple集合 List<Tuple> expectedTuples = listMap1.stream() .map(map -> Tuple.tuple(map.get("Car"), map.get("ElectricCar"))) .collect(Collectors.toList()); // 验证listMap2提取的结果包含所有预期的Tuple softAssertions.assertThat(listMap2) .extracting("Car", "ElectricCar") .containsAll(expectedTuples); });
方案2:自定义提取函数(适配动态键集合)
如果需要验证的键数量不固定,或者需要过滤不存在的键,可以自定义提取逻辑,生成只包含目标键的子Map再对比:
import org.assertj.core.api.SoftAssertions; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; List<String> targetKeys = Arrays.asList("Car", "ElectricCar"); // 自定义函数:从原Map中提取指定键的键值对 Function<Map<String, String>, Map<String, String>> extractTargetKeys = map -> targetKeys.stream() .filter(map::containsKey) .collect(Collectors.toMap(key -> key, map::get)); SoftAssertions.assertSoftly(softAssertions -> { List<Map<String, String>> expectedSubMaps = listMap1.stream() .map(extractTargetKeys) .collect(Collectors.toList()); softAssertions.assertThat(listMap2.stream() .map(extractTargetKeys) .collect(Collectors.toList())) .containsAll(expectedSubMaps); });
方案3:循环验证每个键(精准定位错误)
如果需要对每个键的验证结果单独输出错误信息,可循环遍历目标键,复用单键验证逻辑:
import org.assertj.core.api.SoftAssertions; import java.util.Arrays; import java.util.List; List<String> targetKeys = Arrays.asList("Car", "ElectricCar"); SoftAssertions.assertSoftly(softAssertions -> { for (String key : targetKeys) { Object[] expectedValues = listMap1.stream() .map(m -> m.get(key)) .toArray(); softAssertions.assertThat(listMap2) .extracting(key) .contains(expectedValues); } });
内容的提问来源于stack exchange,提问作者DeepakVerma
相关产品推荐
相关产品推荐

