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.
The assertThat is one of the JUnit methods from the Assert object that can be used to check if a specific value match to an expected one. It primarily accepts 2 parameters. First one if the actual value and the second is a matcher object.
assertThat method is deprecated. Its sole purpose is to forward the call to the MatcherAssert. assertThat defined in Hamcrest 1.3. Therefore, it is recommended to directly use the equivalent assertion defined in the third party Hamcrest library.
Overview. Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.
Assertions. Assertions are utility methods to support asserting conditions in tests; these methods are accessible through the Assert class, in JUnit 4, and the Assertions one, in JUnit 5. In order to increase the readability of the test and of the assertions itself, it's always recommended to import statically the respective class.
Asserts that runnablethrows an exception of type expectedThrowablewhen executed. static void assertTrue(boolean condition) Asserts that a condition is true.
Only failed assertions are recorded. These methods can be used directly: Assert.assertEquals(...), however, they read better if they are referenced through static import: import static org.junit.Assert.*; ...
One of the new assertion introduced in JUnit 5 is assertAll. This assertion allows the creation of grouped assertions, where all the assertions are executed and their failures are reported together. In details, this assertion accepts a heading, that will be included in the message string for the MultipleFailureError, and a Stream of Executable.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With