AssertJ: FlatMap list of lists after calling extracting
Asked Answered
U

1

10

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)

Unaunabated answered 13/7, 2017 at 13:6 Comment(0)
C
19

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

Corydalis answered 14/7, 2017 at 3:51 Comment(1)
map and flatMap to iterable assertions as aliases of extracting and flatExtracting, are now part of assertj-core-3-18-1 : assertj.github.io/doc/#assertj-core-3-18-1-release-notesCoquina

© 2022 - 2024 — McMap. All rights reserved.