【问题标题】:Rewriting "assertTrue" into "assertThat" in JUnit?在 JUnit 中将“assertTrue”重写为“assertThat”?
【发布时间】:2014-07-03 17:20:45
【问题描述】:
List<String> list1 = getListOne();
List<String> list2 = getListTwo();

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

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

如何将其表述为assertThat 语句?

谢谢。

【问题讨论】:

    标签: junit hamcrest


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      此解决方案不使用 Hamcrest Matchers,但对于您的情况来说似乎非常简单:

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

      对于您的场景,使用布尔条件似乎比匹配器更容易。而only assertion that accepts a boolean condition 就是强制你使用错误信息的那个。

      【讨论】:

      • 您的解决方案不适用于 JUnit 的 Assert.assertThat,而仅适用于 org.hamcrest.MatcherAssert.assertThat
      • “唯一接受布尔条件的断言是强制你使用错误消息的断言”? assertThat(value, is(true)) 怎么样?
      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多