【问题标题】:Scalatest: how to check if a collection contains element that satisfies certain criteriaScalatest:如何检查集合是否包含满足某些条件的元素
【发布时间】:2014-11-14 15:01:13
【问题描述】:

假设我有一个书单:

val books = List(
    Book(title="Foo", year=2014),
    Book(title="Bar", year=2014))

如果集合 books 不为空且仅包含 2014 年出版的书籍,如何使用单个表达式进行检查?

【问题讨论】:

标签: scala scalatest matcher


【解决方案1】:

使用matchers:

books should not be empty
books.map(_.year) should contain only (2014)

或者只是:

books.map(_.year) should contain only (2014)

因为此检查断言列表不为空。

【讨论】:

  • 忘了在问题中提及 - 我想用一个匹配的表达式来做。换句话说,我需要一个 Matcher 实例来执行此检查。使用两个should 很容易实现,但我如何将它们合二为一呢?
  • 你为什么要这样做?独立检查每个断言。
  • 第二个检查做你想做的事:如果列表只包含 2014 年的书籍,那么它不为空。
  • 我想编写一个 Matcher 以各种不同的方式检查给定的集合。非空支票只是一个例子。这个想法是找到一种方法如何通过and 和or 组合匹配器,让一个匹配器检查集合属性(例如集合大小),而另一个匹配器检查集合元素。我尝试以这种方式使用 have 匹配器 - book should (have size 1 and contain(have (...))),但这不起作用
  • 也许自定义匹配器是您所追求的? scalatest.org/user_guide/using_matchers#usingCustomMatchers
猜你喜欢
  • 2011-10-07
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 2012-10-01
相关资源
最近更新 更多