2009-07-06 81 views

回答

107

使用JUnit 4.4你可以用Hamcrest代碼一起使用assertThat()很好地集成(不用擔心,它的運使用JUnit,不需要額外的.jar)產生複雜的自我描述斷言包括對集合進行操作的:

import static org.junit.Assert.assertThat; 
import static org.junit.matchers.JUnitMatchers.*; 
import static org.hamcrest.CoreMatchers.*; 

List<String> l = Arrays.asList("foo", "bar"); 
assertThat(l, hasItems("foo", "bar")); 
assertThat(l, not(hasItem((String) null))); 
assertThat(l, not(hasItems("bar", "quux"))); 
// check if two objects are equal with assertThat() 

// the following three lines of code check the same thing. 
// the first one is the "traditional" approach, 
// the second one is the succinct version and the third one the verbose one 
assertEquals(l, Arrays.asList("foo", "bar"))); 
assertThat(l, is(Arrays.asList("foo", "bar"))); 
assertThat(l, is(equalTo(Arrays.asList("foo", "bar")))); 

使用這種方法,你會自動地得到斷言的一個很好的說明,當它失敗。

+1

哦,我還沒有意識到hamcrest已經把它變成了junit發行版。去Nat! – skaffman 2009-07-06 12:49:35

+0

如果我想聲明l由條目(「foo」,「bar」)組成,但沒有其他項目存在 - 是否有一些簡單的語法? – ripper234 2009-07-06 12:57:36

4

不是直接的,沒有。我建議使用Hamcrest,它提供了一套豐富的匹配規則,使用JUnit(以及其它測試框架)

+0

這不會編譯由於某種原因(見http://stackoverflow.com/questions/1092981/hamcrests-hasitems): ArrayList actual = new ArrayList (); ArrayList expected = new ArrayList (); actual.add(1); expected.add(2); assertThat(actual,hasItems(expected)); – ripper234 2009-07-07 15:23:07

1

約阿希姆·紹爾的解決方案是好的,但如果你已經有了,你要驗證在你的結果預期的數組不起作用。如果您在測試中已經生成或持續期望您想要比較結果,或者您希望在結果中合併多個期望,則可能會出現這種情況。因此,而不是使用匹配器,你可以可以只使用List::containsAllassertTrue例如:

@Test 
public void testMerge() { 
    final List<String> expected1 = ImmutableList.of("a", "b", "c"); 
    final List<String> expected2 = ImmutableList.of("x", "y", "z"); 
    final List<String> result = someMethodToTest(); 

    assertThat(result, hasItems(expected1)); // COMPILE ERROR; DOES NOT WORK 
    assertThat(result, hasItems(expected2)); // COMPILE ERROR; DOES NOT WORK 

    assertTrue(result.containsAll(expected1)); // works~ but has less fancy 
    assertTrue(result.containsAll(expected2)); // works~ but has less fancy 
}