重写" assertTrue"进入"断言"在JUnit?

时间:2014-07-03 17:20:46

标签: junit hamcrest

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

鉴于上面的代码,我想使用JUnit assertThat()语句断言list1为空或list1包含list2的所有元素。相当于assertTrue的是:

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

如何将其表达为assertThat声明?

感谢。

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

此解决方案不使用Hamcrest Matchers,但对您的案例来说似乎很简单:

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

对于您的场景,使用布尔条件似乎比使用匹配器更容易。 only assertion that accepts a boolean condition就是强迫您使用错误消息的{{3}}。