检查 Hamcrest 中的列表不为空

发布于 2024-09-17 06:41:41 字数 204 浏览 5 评论 0原文

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

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

assertFalse(list.isEmpty());

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

I was wondering if anyone knew of a way to check if a List is empty using assertThat() and Matchers?

Best way I could see just use JUnit:

assertFalse(list.isEmpty());

But I was hoping that there was some way to do this in Hamcrest.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

花间憩 2024-09-24 06:41:41

嗯,总是有的

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

......但我猜这并不完全是你的意思:)

或者:

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

empty()Matchers 类中的静态。请注意,由于 Hamcrest 1.2 的不稳定泛型,需要将 list 转换为 Collection

以下导入可与 hamcrest 1.3 一起使用

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

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.*;
巴黎夜雨 2024-09-24 06:41:41

此问题已在 Hamcrest 1.3 中修复。下面的代码编译后不会生成任何警告:

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

但如果您必须使用旧版本 - 您可以使用:

hasSize(greaterThan(0)), 而不是有缺陷的 empty() >
(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)));

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

This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:

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

But if you have to use older version - instead of bugged empty() you could use:

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

Example:

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

The most important thing about above solutions is that it does not generate any warnings.
The second solution is even more useful if you would like to estimate minimum result size.

む无字情书 2024-09-24 06:41:41

如果您需要可读的失败消息,您可以通过使用通常的assertEquals和空列表来不使用hamcrest:

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

例如,如果您运行,

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

您会得到

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

If you're after readable fail messages, you can do without hamcrest by using the usual assertEquals with an empty list:

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

E.g. if you run

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

you get

java.lang.AssertionError
Expected :[]
Actual   :[foo, bar]
四叶草在未来唯美盛开 2024-09-24 06:41:41

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

即使泛型问题已在 1.3 中得到解决,此方法的伟大之处在于它适用于任何具有 isEmpty() 方法的类!不仅仅是集合

例如,它也适用于 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"); }
}

Create your own custom IsEmpty TypeSafeMatcher:

Even if the generics problems are fixed in 1.3 the great thing about this method is it works on any class that has an isEmpty() method! Not just Collections!

For example it will work on String as well!

/* 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"); }
}
傲世九天 2024-09-24 06:41:41

这有效:

assertThat(list,IsEmptyCollection.empty())

This works:

assertThat(list,IsEmptyCollection.empty())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文