是 org.junit.Assert.assertThat 比 org.hamcrest.MatcherAssert.a



我是JUnit和Hamcrest的新手,想要最佳实践建议,以便我可以决定首先学习哪个文档。

对于初学者来说,这assertThat方法中哪一种更好?

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

根据去年的一个人的说法,"JUnit有assertThat方法,但hamcrest有自己的assertThat方法,可以做同样的事情。

根据今年早些时候有人的说法,Hamcrest"可能会提供更好的错误消息,因为匹配器被要求描述不匹配"。

很难说在这些帖子中比较了Junit和Hamcrest的哪个版本。 所以我想要一个基于最新发布版本的推荐。

几乎是完全相同的事情。

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

事实上,org.junit.Assert.assertThat 的方法签名是

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

您会注意到使用Hamcrest匹配器。

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

根据马文马,JUnit 4.11 使用 hamcrest 1.3,我相信这是撰写本文时最新的版本。

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

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

所以使用org.hamcrest.MatcherAssert.assertThat.

摘自

JUnit 5的用户指南:

但是,JUnit Jupiter 的 org.junit.jupiter.Assertions 类没有提供像 JUnit 4 的 org.junit.Assert 类中那样接受 Hamcrest MatcherassertThat()方法。相反,建议开发人员使用第三方断言库提供的对匹配器的内置支持。

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

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

因此,即使您使用旧版本的 junit,也最好立即使用hamcrest。

最新更新