检查 Hamcrest 中的列表不为空
我想知道是否有人知道使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
嗯,总是有的
......但我猜这并不完全是你的意思:)
或者:
empty()
是Matchers
类中的静态。请注意,由于 Hamcrest 1.2 的不稳定泛型,需要将list
转换为Collection
。以下导入可与 hamcrest 1.3 一起使用
Well there's always
... but I'm guessing that's not quite what you meant :)
Alternatively:
empty()
is a static in theMatchers
class. Note the need to cast thelist
toCollection
, thanks to Hamcrest 1.2's wonky generics.The following imports can be used with hamcrest 1.3
此问题已在 Hamcrest 1.3 中修复。下面的代码编译后不会生成任何警告:
但如果您必须使用旧版本 - 您可以使用:
hasSize(greaterThan(0)), 而不是有缺陷的
empty()
>(
import static org.hamcrest.number.OrderingComparison.greaterThan;
或import static org.hamcrest.Matchers.greaterThan;
)示例:
上述解决方案最重要的是它不会生成任何警告。
如果您想估计最小结果大小,第二个解决方案会更有用。
This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:
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;
orimport static org.hamcrest.Matchers.greaterThan;
)Example:
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.
如果您需要可读的失败消息,您可以通过使用通常的assertEquals和空列表来不使用hamcrest:
例如,如果您运行,
您会得到
If you're after readable fail messages, you can do without hamcrest by using the usual assertEquals with an empty list:
E.g. if you run
you get
创建您自己的自定义 IsEmpty TypeSafeMatcher:
即使泛型问题已在
1.3
中得到解决,此方法的伟大之处在于它适用于任何具有isEmpty()
方法的类!不仅仅是集合
!例如,它也适用于
String
!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 anisEmpty()
method! Not justCollections
!For example it will work on
String
as well!这有效:
This works: