org.junit.Assert.assert是否比org.hamcrest.MatcherAssert.assert更好?

我是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 “可能会提供更好的错误消息,因为匹配器被称为描述不匹配” 。

在这些post中很难分辨出哪些版本的Junit和Hamcrest被比较了。 所以我想根据最新发布的版本推荐。

几乎是完全相同的事情。

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

实际上org.junit.Assert.assert这是方法签名

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

你会注意到使用hamcrest matchers。

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

根据maven pom,JUnit 4.11使用了hamcrest 1.3,我相信这是写作时最新的。

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

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

所以使用org.hamcrest.MatcherAssert.assertThat

JUnit 5用户指南的摘录:

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

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