Search code examples
assertj

how to verify in assertj that elements are one of


I can't find how to do check with assertj the following (which is very common):

Suppose I have:

 result1 = {"AAA", "BBB"}
 result2 = {"DDD"}

I want to check the values in result is one of these:

String[] valid = String[]{"AAA", "BBB", "CCC"};

using assertj, whould be something as:

assertThat(result1).xxxx(valid);
assertThat(result2).xxxx(valid);

So that result1 would pass check, but result2 not.

contains() does not work (it checks that result contains all valid elements)

I don't want have to create a custom condition for this kind of checking

Any idea?


Solution

  • You can wtite it the other way around:

    assertThat(valid).contains(result1);
    assertThat(valid).contains(result2);
    

    If you insist on having the result on the left and valid on the right side, you can use:

    assertThat(result1).isSubsetOf(Arrays.asList(valid));
    assertThat(result2).isSubsetOf(Arrays.asList(valid));
    

    Or, why not to define the valid as a set, rather than an array?

    Set<String> valid = Sets.newHashSet("AAA", "BBB", "CCC"); //Sets comes from google guava
    assertThat(result1).isSubsetOf(valid);
    assertThat(result2).isSubsetOf(valid);