Search code examples
junithamcrest

Rewriting "assertTrue" into "assertThat" in JUnit?


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

Given the code above, I want to use a JUnit assertThat() statement to assert that either list1 is empty or that list1 contains all the elements of list2. The assertTrue equivalent of this is:

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

How to formulate this into an assertThat statement?

Thanks.


Solution

  • You can do this in the following way:

    // 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)));