Linked Questions

Popular Questions

How to validate in Assertj Collection of Set

Asked by At

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"]]>

Related Questions