list1 = getListOne(); List list2 = getListTwo(); Given the code above,...">

Rewriting "assertTrue" to "assertThat" in JUnit?

List<String> list1 = getListOne();
List<String> list2 = getListTwo();

Given the code above, I want to use the JUnit operator assertThat()to assert that it is either list1empty or that it list1contains all the elements list2. Equivalent assertTrue:

assertTrue(list1.isEmpty() || list1.containsAll(list2)).

How to formulate this in the instructions assertThat?

Thank.

+4
source share
2 answers

You can do it as follows:

// Imports
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.collection.IsEmptyIterable.emptyIterableOf;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

// First solution
assertThat(list1,
    either(emptyIterableOf(String.class))
    .or(hasItems(list2.toArray(new String[list2.size()]))));

// Second solution, this will work ONLY IF both lists have items in the same order.
assertThat(list1,
    either(emptyIterableOf(String.class))
        .or(is((Iterable<String>) list2)));
+4
source

This solution does not use Hamcrest Matchers, but for your case it seems very simple:

assertThat("Custom Error message", list1.isEmpty() || list1.containsAll(list2));

, . , , , .

0

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


All Articles