2

I have method which returns List of records. Each record have Set as field.

public class R {
    public final Set s;
}

I have list of all expected Set - like:

Set<String> set1 = new HashSet<String>(); set1.add("s1");
Set<String> set2 = new HashSet<String>(); set1.add("s2");
Set<String> set3 = new HashSet<String>(); set1.add("s3");

I want to validate in easy way using AssertJ (ver. 3.11.1) that response List<R> contains all defined Set or at least aggregation of all elements from these sets are equals to aggregation of elements from sets set1, set2, set3

NOTE: solution bellow is not working:

Set allElements = new HashSet<String>();
allElements.addAll(set1);
allElements.addAll(set2);
allElements.addAll(set3);

List<R> result = foo();
org.assertj.core.api.Assertions.assertThat(result)
    .extracting(record -> record.s)
    .containsOnly(allElements);

I got:

java.lang.AssertionError: 
Expecting:
  <[["s1.1", "s1.2"],
    ["s2.1", "s2.2"],
    ["s3.1", "s3.2"]]>
to contain only:
  <[["s1.1",
    "s1.2",
    "s2.1",
    "s2.2",
    "s3.1",
    "s3.2"]]>
THM
  • 579
  • 6
  • 25
  • Unrelated: better read https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – GhostCat Feb 01 '19 at 10:33
  • And it is confusing: you say "List of records", but your code shows just ONE R result object? So: please read [mcve] carefully and make sure that such details are consistent. – GhostCat Feb 01 '19 at 10:35

2 Answers2

6

Looks like containsExactlyInAnyOrderElementsOf is the answer

solution is:

Set<Set<String>> referralSet = new HashSet<>();
referralSet.add(set1);
referralSet.add(set2);
referralSet.add(set3);

org.assertj.core.api.Assertions.assertThat(result)
        .extracting(record -> record.s)
        .containsExactlyInAnyOrderElementsOf(referralSet);
THM
  • 579
  • 6
  • 25
1

Looks like a use case for flatExtracting, try something like:

.assertThat(result).flatExtracting(record -> record.s)
                   .containsExactlyInAnyOrderElementsOf(referralSet);
Joel Costigliola
  • 6,308
  • 27
  • 35