【问题标题】:CollectionAssert in jUnit?jUnit中的CollectionAssert?
【发布时间】:2009-07-06 12:25:27
【问题描述】:

是否有与 NUnit 的 CollectionAssert 平行的 jUnit?

【问题讨论】:

    标签: java junit nunit assertion


    【解决方案1】:

    使用 JUnit 4.4,您可以使用 assertThat()Hamcrest 代码(不用担心,它与 JUnit 一起提供,不需要额外的 .jar)来生成复杂的自描述断言,包括那些操作关于收藏:

    import static org.junit.Assert.assertThat;
    import static org.junit.matchers.JUnitMatchers.*;
    import static org.hamcrest.CoreMatchers.*;
    
    List<String> l = Arrays.asList("foo", "bar");
    assertThat(l, hasItems("foo", "bar"));
    assertThat(l, not(hasItem((String) null)));
    assertThat(l, not(hasItems("bar", "quux")));
    // check if two objects are equal with assertThat()
    
    // the following three lines of code check the same thing.
    // the first one is the "traditional" approach,
    // the second one is the succinct version and the third one the verbose one 
    assertEquals(l, Arrays.asList("foo", "bar")));
    assertThat(l, is(Arrays.asList("foo", "bar")));
    assertThat(l, is(equalTo(Arrays.asList("foo", "bar"))));
    

    使用这种方法,您将在断言失败时自动获得对断言的良好描述。

    【讨论】:

    • 哦,我没有意识到 hamcrest 已经进入了 junit 发行版。去纳特!
    • 如果我想断言 l 由项目(“foo”,“bar”)组成,但不存在其他项目 - 是否有一些简单的语法?
    • 使用上面的代码 sn-p 并抛出一个额外的 assertTrue(l.size() == 2)
    • 呸,丑。在 NUnit 中是 CollectionAssert.AreEqual( Collection expected, Collection actual );
    • Google 找到了我正在寻找的另一个 Stackoverflow 答案!
    【解决方案2】:

    不直接,不。我建议使用Hamcrest,它提供了一组丰富的匹配规则,可以很好地与jUnit(和其他测试框架)集成

    【讨论】:

    【解决方案3】:

    看看 FEST Fluent Assertions。恕我直言,它们比 Hamcrest 更方便使用(并且同样强大、可扩展等),并且由于流畅的界面而具有更好的 IDE 支持。见https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions

    【讨论】:

    • 在 2017 年,似乎有更多人在使用 FEST 的一个名为 AssertJ 的分支。
    【解决方案4】:

    Joachim Sauer 的解决方案很不错,但如果您的结果中已经有一系列想要验证的期望,则该解决方案将不起作用。当您在测试中已经有一个生成的或持续的期望要与结果进行比较时,或者您可能有多个期望合并到结果中时,可能会出现这种情况。因此,您可以只使用List::containsAllassertTrue 而不是使用匹配器,例如:

    @Test
    public void testMerge() {
        final List<String> expected1 = ImmutableList.of("a", "b", "c");
        final List<String> expected2 = ImmutableList.of("x", "y", "z");
        final List<String> result = someMethodToTest(); 
    
        assertThat(result, hasItems(expected1)); // COMPILE ERROR; DOES NOT WORK
        assertThat(result, hasItems(expected2)); // COMPILE ERROR; DOES NOT WORK
    
        assertTrue(result.containsAll(expected1));  // works~ but has less fancy
        assertTrue(result.containsAll(expected2));  // works~ but has less fancy
    }
    

    【讨论】:

    • 您可以随时使用hasItems(expected1.toArray(new String[expected1.size()]))。它会给你更好的失败信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 2017-06-16
    • 2011-05-04
    • 1970-01-01
    • 2015-01-28
    • 2012-12-03
    相关资源
    最近更新 更多