matchers lists example java collections junit hamcrest

java - lists - hamcrest maven



Verificando que una Lista no esté vacía en Hamcrest (4)

Me preguntaba si alguien sabía de una forma de verificar si una Lista está vacía usando assertThat() y Matchers ?

La mejor manera que pude ver es usar JUnit:

assertFalse(list.isEmpty());

Pero esperaba que hubiera alguna manera de hacer esto en Hamcrest.


Cree su propio IsEmpty TypeSafeMatcher personalizado:

Incluso si los problemas con los genéricos se solucionan en 1.3 lo mejor de este método es que funciona en cualquier clase que tenga un método isEmpty() . ¡No solo Collections !

¡Por ejemplo, también funcionará en String !

/* Matches any class that has an <code>isEmpty()</code> method * that returns a <code>boolean</code> */ public class IsEmpty<T> extends TypeSafeMatcher<T> { @Factory public static <T> Matcher<T> empty() { return new IsEmpty<T>(); } @Override protected boolean matchesSafely(@Nonnull final T item) { try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); } catch (final NoSuchMethodException e) { return false; } catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } } @Override public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); } }


Bueno, siempre hay

assertThat(list.isEmpty(), is(false));

... pero supongo que eso no es lo que querías decir :)

Alternativamente:

assertThat((Collection)list, is(not(empty())));

empty() es estático en la clase Matchers . Tenga en cuenta la necesidad de lanzar la list a la Collection , gracias a los genéricos wonky de Hamcrest 1.2.

Las siguientes importaciones se pueden usar con hamcrest 1.3

import static org.hamcrest.Matchers.empty; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.*;


Esto está arreglado en Hamcrest 1.3. El siguiente código compila y no genera ninguna advertencia:

// given List<String> list = new ArrayList<String>(); // then assertThat(list, is(not(empty())));

Pero si tiene que usar una versión anterior, en lugar de tener una carpeta empty() , podría usar:

  • not(hasSize(0))
    ( import static org.hamcrest.collection.IsCollectionWithSize.hasSize; o
    import static org.hamcrest.Matchers.hasSize; )

  • hasSize(greaterThan(0))
    ( import static org.hamcrest.number.OrderingComparison.greaterThan; o
    import static org.hamcrest.Matchers.greaterThan; )

Ejemplo:

// given List<String> list = new ArrayList<String>(); // then assertThat(list, not(hasSize(0))); // or assertThat(list, hasSize(greaterThan(0)));

Lo más importante de las soluciones anteriores es que no genera ninguna advertencia. La segunda solución es aún más útil si desea estimar el tamaño mínimo del resultado.


Si buscas mensajes de error legibles, puedes prescindir de Hamcrest utilizando los assertEquals habituales con una lista vacía:

assertEquals(new ArrayList<>(0), yourList);

Ej. Si corres

assertEquals(new ArrayList<>(0), Arrays.asList("foo", "bar");

usted obtiene

java.lang.AssertionError Expected :[] Actual :[foo, bar]