¿Existe un jUnit paralelo al NUnit's CollectionAssert?CollectionAssert in jUnit?
Respuesta
El uso de JUnit 4.4 se puede utilizar assertThat()
junto con el código Hamcrest (no se preocupe, es enviado con JUnit, sin necesidad de un extra de .jar
) 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"))));
Usando este enfoque se le automagicamente obtener una buena descripción de la aserción cuando falla.
No directamente, no. Sugiero el uso de Hamcrest, que proporciona un rico conjunto de reglas de concordancia que se integra muy bien con jUnit (y otras infraestructuras de prueba)
Esto no compila por alguna razón (ver http://stackoverflow.com/questions/1092981/hamcrests-hasitems): ArrayList
Eche un vistazo a FEST Fluent Assertions. En mi humilde opinión, son más cómodos de usar que Hamcrest (e igualmente potentes, extensibles, etc.) y tienen mejor soporte IDE gracias a una interfaz fluida. Ver https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions
En 2017 parece que cada vez más personas usan una rama de FEST llamada AssertJ. – Max
La solución de Joachim Sauer es buena pero no funciona si ya tiene una serie de expectativas que desea verificar en su resultado. Esto puede surgir cuando ya tiene una expectativa generada o constante en sus pruebas para la que desea comparar un resultado, o tal vez tiene múltiples expectativas que espera fusionar en el resultado. Así que en lugar de utilizar comparadores puede simplemente usar 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
}
- 1. Prueba de unidad IList con CollectionAssert
- 2. junit annotation
- 3. JUnit - assertSame
- 4. Servidor de prueba con JUnit
- 5. Ant JUnit ClassNotFoundException
- 6. Las diferencias entre JUnit 3 y JUnit 4
- 7. ¿Cómo escribo: else in condp in Clojure?
- 8. JUnit ciclo de vida
- 9. JUnit TestCase objeto instanciación
- 10. java.lang.NoClassDefFoundError en junit
- 11. básico jUnit Preguntas
- 12. Alternativas a JUnit
- 13. Interceptar JUnit Assert functions
- 14. Cómo obtener JUnit versión
- 15. Método protegido Junit
- 16. Jenkins y JUnit
- 17. Prueba JUnit para System.out.println()
- 18. Junit output y OutOfMemoryError
- 19. JUnit Eclipse Plugin?
- 20. jUnit fallar() convenciones
- 21. JUnit anotación personalizada
- 22. ExpectedException en jUnit?
- 23. JUnit termina subprocesos secundarios
- 24. JUnit y Android?
- 25. Agrupando pruebas de JUnit
- 26. Junit con new Date()
- 27. @parameters en Junit 4
- 28. JUnit Exception Testing
- 29. Mockito, JUnit y Spring
- 30. Prueba FragmentActivity Junit
Ooh, no me había dado cuenta de que Hamcrest había llegado a la distribución de junio. ¡Ve a Nat! – skaffman
Si quiero afirmar que l está compuesto de elementos ("foo", "bar"), pero no existen otros elementos, ¿existe alguna sintaxis fácil para eso? – ripper234
Utilice el fragmento de código anterior y agregue un assertTrue adicional (l.size() == 2) – aberrant80