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

给定上面的代码,我想使用JUnit assertThat()语句来断言list1为空或list1包含list2的所有元素。等效的assertTrue是:
assertTrue(list1.isEmpty() || list1.containsAll(list2))

如何将其表达为assertThat语句?

谢谢。

最佳答案

您可以通过以下方式执行此操作:

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

关于junit - 在JUnit中将 "assertTrue"重写为 "assertThat"吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24559799/

10-12 00:21
查看更多