2009-07-06 10 views

risposta

107

Utilizzando JUnit 4.4 è possibile utilizzare assertThat() insieme al codice Hamcrest (non preoccupatevi, è spedito con JUnit, senza bisogno di un extra .jar) per la produzione di complessi autodescrittivo afferma compresi quelli che operano su collezioni:

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")))); 

con questo approccio si automagicamente ottenere una buona descrizione della asserzione quando non riesce.

+1

Ooh, non mi ero reso conto che hamcrest fosse arrivato nella distro junit. Vai Nat! – skaffman

+0

Se voglio affermare che l è composto da elementi ("foo", "bar"), ma non esistono altri elementi - esiste una sintassi semplice per questo? – ripper234

+0

Utilizzare lo snippet di codice precedente e inserire un ulteriore assertTrue (l.size() == 2) – aberrant80

4

Non direttamente, n. Suggerisco l'uso di Hamcrest, che fornisce un ricco set di regole di corrispondenza che si integra perfettamente con JUnit (e di altri framework di test)

+0

Questo non viene compilato per qualche motivo (vedi http://stackoverflow.com/questions/1092981/hamcrests-hasitems): ArrayList actual = new ArrayList (); ArrayList expected = new ArrayList (); actual.add (1); expected.add (2); assertThat (actual, hasItems (previsto)); – ripper234

2

Dai un'occhiata alle FEST Fluent Assertions. IMHO sono più convenienti da usare di Hamcrest (e altrettanto potenti, estendibili, ecc.) E hanno un migliore supporto IDE grazie all'interfaccia fluida. Vedi https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions

+0

Nel 2017 sembra che sempre più persone stiano usando una filiale di FEST chiamata AssertJ. – Max

1

La soluzione di Joachim Sauer è buona, ma non funziona se hai già una serie di aspettative che vuoi verificare nel risultato. Ciò potrebbe verificarsi quando hai già un'aspettativa generata o costante nei test a cui desideri confrontare un risultato o forse hai aspettative multiple che ti aspetti di unire nel risultato. Così, invece di usare matchers è possibile può semplicemente utilizzare List::containsAll e assertTrue Per esempio:

@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 
}