Domanda

C'è un JUnit parallelo a CollectionAssert ?

È stato utile?

Soluzione

Utilizzando JUnit 4.4 è possibile utilizzare assertThat() insieme alla Hamcrest codice (non preoccupatevi, è fornito con JUnit, senza bisogno di un .jar extra) 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.

Altri suggerimenti

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

Date un'occhiata a FEST Fluent asserzioni. IMHO sono più comodo da usare rispetto Hamcrest (e altrettanto potente, estensibile, ecc) e hanno un migliore supporto IDE grazie alla interfaccia fluida. Vedere https://github.com/alexruiz/fest- asserire-2.x / wiki / Usando-Fest-asserzioni

La soluzione di Joachim Sauer è bello, ma non funziona se si dispone già di una serie di aspettative che si desidera verificare sono nel vostro risultato. Questo potrebbe venire quando si dispone già di un aspettativa generata o costante nei test che si desidera confrontare un risultato, o forse avete più aspettative che ci si aspetta da 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
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top