Search code examples
javajava-8assertj

AssertJ: FlatMap list of lists after calling extracting


So I have a Map of String/String list pairs, and what I want to do is after extraction, combine the returned lists into one list on which i can perform more assertions:

MyTest.java

Map<String, List<String>> testMap  = new HashMap<>();
List<String> nameList = newArrayList("Dave", "Jeff");
List<String> jobList = newArrayList("Plumber", "Builder");
List<String> cityList = newArrayList("Dover", "Boston");

testMap.put("name", nameList);
testMap.put("job", jobList);
testMap.put("city", cityList);

assertThat(testMap).hasSize(3)
    .extracting("name", "city")
    //not sure where to go from here to flatten list of lists
    // I want to do something like .flatMap().contains(expectedValuesList)

When I call extracting, it pulls out the list values into a list of lists, which is fine, but I cant call flatExtracting after that as there are no property names to pass in, and from what I've read it doesn't seem like a custom extractor would be appropriate(or else I'm not entirely sure how to put it together). Is there another way to flatten the list of lists im getting back? I could go a slightly longer route and do assertions on the list of lists, or use a lambda before the assert to collect the results but I'd like to keep the assertion as one(e.g. some map asserts then chain some assertions on the contents)


Solution

  • flatExtracting is not in the map assertions API (yet), what you can instead is:

    assertThat(testMap)
            .hasSize(3)
            .extracting("name", "city", "job")
            .flatExtracting(list -> ((List<String>) list))
            .contains("Dave", "Jeff", "Plumber", "Builder", "Dover", "Boston");
    

    I ended creating https://github.com/joel-costigliola/assertj-core/issues/1034 to support this use case