Search code examples
assertj

Using Assertj how to verify two hashmap list List<Map<String, String>> with multiple keys


I have two hashmap list and want to check the value present against the given key is same.

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

using below approach I am able to verify with single key

SoftAssertions.assertSoftly(softAssertions -> softAssertions.assertThat(listMap2)
          .extracting("Car")
          .contains(listMap1.stream().map(m -> m.get("Car")).toArray()));

Solution

  • Your example only shows singleton list so it looks like it boils down to check that the common keys from the two maps have the same value. Could you show an example with lists that contain multiple maps and what you expect from the assertions?

    In the meantime, I was able to do the following (even though I'm not sure that addresses your issue):

    Version 1
    Extracting multiple values that are returned as a Tuple and check that the tuple has the correct content.

    assertThat(listMap2).extracting("Car", "ElectricCar")
                        .containsExactly(tuple("Toyota", "Tesla"));
    

    Version 2
    Instead of hardcoding "Toyota" and "Tesla", I assume you want to get the value from listMap1 with for example a helper method (named valueOf here that you can write easily)

    assertThat(listMap2).extracting("Car", "ElectricCar")
                        .containsExactly(tuple(valueOf("Car", listMap1), 
                                               valueOf("ElectricCar", listMap1)));
    

    This is not a straightforward solution, I would recommend to write an helper method like checkValuesMatchForSameKeys(List<Map<String, String>> listMap1, Map<String, String> map2) that you could use as:

    assertThat(listMap2).allSatisfy(map2 -> checkValuesMatchForSameKeys(listMap1, map2));