2014-12-02 86 views
10

我是JUnit和Hamcrest的新手,希望獲得最佳實踐建議,以便我可以決定首先學習哪些文檔。是org.junit.Assert.assert比org.hamcrest.MatcherAssert.assert那個更好嗎?

對於初學者,這些assertThat方法哪個更好?

  1. org.junit.Assert.assertThat(來自的junit-4.11.jar)
  2. org.hamcrest.MatcherAssert.assertThat(從hamcrest芯-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進行了比較。所以我想要一個基於最新發布版本的建議。

回答

17

這就是差不多完全一樣的東西。

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 2個細微的差別,使得它更加有用:

  1. 當比賽失敗,錯誤消息包括什麼不同而不是「預期X但是Y」。定製hamcrest匹配器可以包括關於究竟是錯的通過實施describeMismatch()
  2. 更詳細的信息assertThat簽名是使用T actual, Matcher<? super T> matcher hamcrest允許的匹配是超級類型(如匹配器來比較整數和雙精度)不同。這通常不重要,但是當你需要它時,這是一個很好的功能。

因此,使用org.hamcrest.MatcherAssert.assertThat

+0

謝謝dkatzel,知道JUnit沒有經常更新是很有幫助的,所以我可能想包含我自己的Hamcrest版本。這就是我正在尋找的那種知識,所以再次感謝。 – 2014-12-02 18:40:53

+0

@MichaelOsofsky我已經更新了我的答案,我發現他們略有不同,我現在更喜歡hamcrest。 – dkatzel 2014-12-02 18:47:58

+0

謝謝@dkatzel,這真的很有幫助。 – 2014-12-02 18:55:09

0

摘錄從JUnit 5's User Guide

然而,JUnit的木星的org.junit.jupiter.Assertions類不提供assertThat()方法像在JUnit的發現4的org.junit.Assert類,它接受一個Hamcrest Matcher 。相反,鼓勵開發人員使用由第三方斷言庫提供的對匹配器的內置支持。

我認爲對於JUnit 4,Hamcrest的assertThat是(正式)首選。