Pregunta

¿Hay una jUnit paralelo a CollectionAssert ?

¿Fue útil?

Solución

El uso de JUnit 4.4 se puede utilizar junto con el assertThat() Hamcrest código (no se preocupe, se envía con JUnit, sin necesidad de un .jar adicional) para producir complejos auto-descripción afirma incluyendo los que operan en las colecciones:

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 este enfoque se le automagicamente obtener una buena descripción de la aserción cuando falla.

Otros consejos

No directamente, no. I sugieren el uso de Hamcrest , que proporciona un rico conjunto de reglas de concordancia que se integra muy bien con jUnit (y otra marcos de prueba)

Tome un vistazo a FEST Fluido afirmaciones. En mi humilde opinión que son más convenientes de utilizar que Hamcrest (e igualmente poderosa y extensible, etc.) y tienen un mejor soporte IDE gracias a la interfaz fluida. Ver https://github.com/alexruiz/fest- valer-2.x / wiki / Uso-Fest-afirmaciones

La solución de Joachim Sauer es agradable, pero no funciona si ya dispone de una serie de expectativas que desea verificar son en su resultado. Esto podría llegar cuando ya se tiene una expectativa generada o constante en sus pruebas que se desea comparar el resultado de, o tal vez usted tiene múltiples expectativas espera que se fusionaron en el resultado. Así que en lugar de utilizar comparadores se puede usar simplemente List::containsAll y assertTrue Por ejemplo:

@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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top