12
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.

uthark
  • 5,333
  • 2
  • 43
  • 59
r123454321
  • 3,323
  • 11
  • 44
  • 63

2 Answers2

8

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)));
uthark
  • 5,333
  • 2
  • 43
  • 59
0

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

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

For your scenario seems a lot easier use a boolean condition than a matcher. And the only assertion that accepts a boolean condition is this one that forces you to use an error message.

Ale Sequeira
  • 2,039
  • 1
  • 11
  • 19
  • 1
    Your solution does not work wth JUnit's `Assert.assertThat` but rather only with `org.hamcrest.MatcherAssert.assertThat`. – Sled Aug 09 '14 at 18:38
  • 7
    "The only assertion that accepts a boolean condition is this one that forces you to use an error message"? How about `assertThat(value, is(true))`? – spaaarky21 Mar 05 '17 at 22:50