【问题标题】:Is there a version of JUnit assertThat which uses the Hamcrest 'describeMismatch' functionality?是否有使用 Hamcrest 'describeMismatch' 功能的 JUnit assertThat 版本?
【发布时间】:2011-04-24 08:35:46
【问题描述】:

在我尝试过的每个 JUnit 版本(最高 4.8.1)中,失败的 assertThat 将显示如下错误消息:

预期:[describeTo]
得到:[对象的字符串表示]

换句话说,它将显示对象的 toString(),而不是来自 Matcher 的不匹配描述。如果我使用 org.hamcrest.MatcherAssert.assertThat 中的 assertThat,那么它将调用“describeMismatch”并显示更有用的错误消息。

我是在错误地使用 Junit,还是目前没有可以满足我需求的 JUnit 版本?大多数人会使用 Hamcrest assertThat 吗?

【问题讨论】:

    标签: java unit-testing junit hamcrest


    【解决方案1】:

    简短回答:不。

    据我所知,最新版本的 Hamcrest (1.2) 引入了与 JUnit 当前所依赖的 1.1 版本不兼容的类型签名。我不确定 Hamcrest 的变化造成的损害程度(可以这么说),但 JUnit 团队似乎并不急于升级(参见open issue)。

    我不完全确定我已经解决了我的问题,但我打算使用MatcherAssert.assertThat()。这可能需要特定版本的 JUnit(我相信是 junit-dep-xxx),它不会与 Hamcrest 发生类路径冲突。否则,当assertThat() 拨打describeMismatch() 时,您可能会收到NoSuchMethodErrors

    【讨论】:

    • 谢谢。那么,您使用 Hamcrest assertThat 还是什么?
    【解决方案2】:

    是的,这是由this commitJUnit 4.11 中修复的:

    正如 Hamcrest 的 Steve Freeman 所指出的,Matcher 界面现在 有一个额外的方法 describeMismatch。为了安全地抓住这样的 未来的改进,使用 MatcherAssert 代替 复制它的实现。

    upgrade to Hamcrest 1.3(也在 4.11 中)一起,这两个版本可以很好地协同工作。

    【讨论】:

      【解决方案3】:

      使用other version assertThat(String, T, Matcher<T>) 并在第一个参数中编写您自己的消息,以便更好地描述失败。

      【讨论】:

      • 谢谢,鲍里斯。这是创建描述的一种好方法。但是,我更喜欢使用 Matcher 可以通过其“describeMismatch”方法生成的内置错误消息。
      猜你喜欢
      • 2017-09-02
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2011-08-17
      • 2018-02-01
      • 2020-11-03
      相关资源
      最近更新 更多