Experience either one thing holds or in AssertJ

I am going to convert some tests from Hamcrest to AssertJ. In Hamcrest, I use the following snippet:

assertThat(list, either(contains(Tags.SWEETS, Tags.HIGH)) .or(contains(Tags.SOUPS, Tags.RED))); 

That is, the list can be either this or that. How can I express this in AssertJ? The anyOf function (of course, any other than any other, but this will be the second question) accepts Condition ; I realized this myself, but it seems to me that this should be commonplace.

+6
source share
2 answers

No, this is the area where Hamcrest is better than AssertJ.

To write the following statement:

 Set<String> goodTags = newLinkedHashSet("Fine", "Good"); Set<String> badTags = newLinkedHashSet("Bad!", "Awful"); Set<String> tags = newLinkedHashSet("Fine", "Good", "Ok", "?"); // contains is statically imported from ContainsCondition // anyOf succeeds if one of the conditions is met (logical 'or') assertThat(tags).has(anyOf(contains(goodTags), contains(badTags))); 

you need to create this condition:

 import static org.assertj.core.util.Lists.newArrayList; import java.util.Collection; import org.assertj.core.api.Condition; public class ContainsCondition extends Condition<Iterable<String>> { private Collection<String> collection; public ContainsCondition(Iterable<String> values) { super("contains " + values); this.collection = newArrayList(values); } static ContainsCondition contains(Collection<String> set) { return new ContainsCondition(set); } @Override public boolean matches(Iterable<String> actual) { Collection<String> values = newArrayList(actual); for (String string : collection) { if (!values.contains(string)) return false; } return true; }; } 

Perhaps this is not the case if you expect that the presence of your tags in one collection means that they are not in another.

+4
source

Inspired by this thread, you can use this small repo that I have compiled, which adapts the Matrix Matcher API to the AssertJ conditions API. Also includes a handy shell conversion script.

+2
source

Source: https://habr.com/ru/post/977706/


All Articles