【问题标题】:Is org.junit.Assert.assertThat better than org.hamcrest.MatcherAssert.assertThat?org.junit.Assert.assertThat 比 org.hamcrest.MatcherAssert.assertThat 好吗?
【发布时间】:2014-12-02 18:28:45
【问题描述】:

我是 JUnit 和 Hamcrest 的新手,希望获得最佳实践建议,以便我可以决定首先研究哪些文档。

对于初学者,assertThat 方法中哪个更好?

  1. org.junit.Assert.assertThat(来自 junit-4.11.jar)
  2. org.hamcrest.MatcherAssert.assertThat(来自 hamcrest-core-1.3.jar)

据去年的一个人说,"JUnit has the assertThat method, but hamcrest has its own assertThat method that does the same thing."

据今年早些时候有人说,Hamcrest "could potentially give better error messages because the matcher is called to describe the mismatch"

很难说这些帖子中比较了哪些版本的 Junit 和 Hamcrest。因此,我想要一个基于最新发布版本的建议。

【问题讨论】:

    标签: java junit hamcrest


    【解决方案1】:

    几乎一模一样。

    JUnit 的最新版本现在包括 hamcrest。

    其实 org.junit.Assert.assertThat 的方法签名是

    public static <T> void assertThat(T actual,
                                  org.hamcrest.Matcher<T> matcher)
    

    你会注意到它使用了 hamcrest 匹配器。

    您可能仍希望包含您自己的 hamcrest 版本,因为 JUnit 不经常更新,并且可能并不总是使用最新版本的 hamcrest。

    根据 maven pom, JUnit 4.11 使用 hamcrest 1.3,我认为这是撰写本文时最新的。

    编辑 我刚刚阅读了您的第二篇文章 http://blog.code-cop.org/2014/02/assert-or-matcherassert.html,它描述了 hamcrest assertThat 的两个细微差别,使其更有用:

    1. 当匹配失败时,错误消息会包含不同的内容,而不是“预期的 X 但为 Y”。通过实现describeMismatch(),自定义 hamcrest 匹配器可能包含有关确切错误的更多详细信息。
    2. assertThat 签名在 hamcrest 中使用 T actual, Matcher&lt;? super T&gt; matcher 不同,它允许匹配器成为超级类型(如匹配器来比较整数和双精度)。这通常无关紧要,但是当您需要它时,这是一个不错的功能。

    所以使用org.hamcrest.MatcherAssert.assertThat

    【讨论】:

    • 谢谢 dkatzel,知道 JUnit 不经常更新很有帮助,所以我可能想包含我自己的 Hamcrest 版本。正是我正在寻找的那种知识,所以再次感谢。
    • @MichaelOsofsky 我更新了我的答案,发现它们略有不同,我现在更喜欢 hamcrest。
    • 谢谢@dkatzel,这真的很有帮助。
    • 谢谢@dkatzel。您知道是否可以控制 Eclipse 的内容辅助功能如何解析哪个 assertThat?我在 Eclipse 中使用 Maven。 Eclipse 内容辅助功能只告诉我有关 Junit 或 Hamcrest 的信息,但不是两者都告诉我,即使我已经导入了 import static org.hamcrest.MatcherAssert.*import static org.junit.Assert.*
    • 对不起,我不知道。我的猜测是 eclipse 变得很困惑,因为这两个包都有一个assertThat。我不会依赖使用“*”进行批量静态导入。而只是import static org.hamcrest.MatcherAssert.assertThat;
    【解决方案2】:

    摘自JUnit 5's User Guide

    但是,JUnit Jupiter 的 org.junit.jupiter.Assertions 类不提供 assertThat() 方法,就像在 JUnit 4 的 org.junit.Assert 类中发现的那样,它接受 Hamcrest Matcher。相反,鼓励开发人员使用第三方断言库提供的对匹配器的内置支持。

    我认为对于 JUnit 4,Hamcrest 的 assertThat(官方)是首选。

    【讨论】:

      【解决方案3】:

      在 junit 4.13 中,方法 org.junit.Assert.assertThat() 被标记为已弃用,建议使用 org.hamcrest.MatcherAssert.assertThat()

      所以最好立即使用 hamcrest,即使您使用的是旧版本的 junit。

      【讨论】:

        猜你喜欢
        • 2011-06-23
        • 1970-01-01
        • 2017-05-06
        • 2011-09-16
        • 2019-04-29
        • 2021-08-20
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多