154

我想知道是否有人知道使用assertThat()and检查列表是否为空的方法Matchers

我能看到的最好的方法就是使用 JUnit:

assertFalse(list.isEmpty());

但我希望在 Hamcrest 有一些方法可以做到这一点。

4

5 回答 5

182

Well there's always

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

... but I'm guessing that's not quite what you meant :)

Alternatively:

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

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;
于 2010-09-02T20:47:26.397 回答
82

这在 Hamcrest 1.3 中已修复。下面的代码编译并且不会产生任何警告:

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

但是,如果您必须使用旧版本 - 而不是窃听empty(),您可以使用:

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

例子:

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

上述解决方案最重要的是它不会产生任何警告。如果您想估计最小结果大小,则第二种解决方案更加有用。

于 2012-01-17T12:02:53.830 回答
5

如果您在阅读失败消息后,您可以通过使用带有空列表的常用 assertEquals 来不使用 hamcrest:

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

例如,如果你跑

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

你得到

java.lang.AssertionError
Expected :[]
Actual   :[foo, bar]
于 2013-11-23T02:26:55.793 回答
0

创建您自己的自定义 IsEmpty TypeSafeMatcher:

即使泛型问题在1.3这个方法的伟大之处得到了解决,它也适用于任何具有isEmpty()方法的类!不只是Collections

例如,它也将起作用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"); }
}
于 2015-09-14T20:15:53.793 回答
0

这有效:

assertThat(list,IsEmptyCollection.empty())
于 2020-04-17T18:54:50.420 回答