2012-10-22 120 views

回答

2

主要是爲了便於閱讀。 例如:

StringAssert.StartsWith('abc', s); 

可能是更具可讀性比:

Assert.True(s.StartsWith('abc')) 

一些斷言,雖然做其他有用的東西,如Assert.Fail();

4

在JUnit中我更喜歡使用Hamcrest(assertThat)爲我所有的匹配。我覺得它提供了更多可讀的斷言。有大量可用的匹配器,並且錯誤消息更加豐富。

例如,假設您有一個List<String>。在assertTrue它可能是:

assertTrue(myList.size() == 3); 

錯誤消息這一點,如果expected true, got false。與此相比,Hamcrest,

assertThat(myList, IsCollectionWithSize.hasSize(3)); 

或靜態導入

assertThat(myList, hasSize(3)); 
assertThat(myList, containsInOrder("first", "second")); 

此錯誤消息是expected collection with size 3, got list["blah", "blah" ...]

有額外的匹配像containsStringIsIterableContainingInOrderIsIterableContainingInAnyOrder,等,等,等。

Hamcrest

1

我想它提供了一些可讀性。 Assert.IsNotNull(obj)在眼睛上比Assert.True(obj!= null)更容易。爲了便於閱讀,

0

。測試應該是你的代碼的文檔。

只要有可能,我使用fest assert與普通舊assertXXX沒有任何表達式。如果不可能的話(或者需要對謂詞做很多工作),我使用hamcrest。使用複雜的表達式與assertXXX是我的最後一招