用于检查一个集合是否包含另一个集合的元素的 ScalaTest 匹配器语法
ScalaTest matcher syntax for checking whether one collection contains the elements of another
在 ScalaTest 中很容易检查容器是否包含某些元素:
val theList = List(1, 2, 3, 4, 5)
theList should contain allOf(5, 3, 1) // passes
但是,如果您已经有了包含要检查的那些元素的列表,则不清楚如何使用它。下面的代码无法编译,因为 allOf()
只接受集合元素,而不是集合,并且至少需要两个元素。
val theList = List(1, 2, 3, 4, 5)
val expected = List(5, 3, 1)
theList should contain allOf(expected) // doesn't compile
因为 Scala List
没有 containsAll()
,你甚至不能这样做:
val theList = List(1, 2, 3, 4, 5)
theList.containsAll(expected) should be(true) // doesn't compile
现在我正在做以下事情,但我对此并不满意:
for(x <- expected) {
theList should contain(x)
}
是否有更流畅/Scala-ish/标准的方式来做出这个断言?
您可以使用隐式 类 添加缺少的方法
trait AllElementsOf {
implicit class AllElementsOf[L <: GenTraversable[_]](resultOfContainWord: ResultOfContainWord[L]) {
def allElementsOf(l: L)(implicit aggregating: Aggregating[L]) = {
val list = l.toList
assume(list.size >= 2, s"Expected to see list longer than 2")
resultOfContainWord.allOf(list(0), list(1), list.drop(2):_*)
}
}
}
class AllOfListSpec extends FlatSpec with ShouldMatchers with AllElementsOf {
"list" should "contain all of another list" in {
val theList = List(1, 2, 3, 4, 5)
val expected = List(5, 3, 1)
theList should contain allElementsOf expected
}
}
更新
官方 allElementsOf 将在 scalatest 3.0
在 ScalaTest 中很容易检查容器是否包含某些元素:
val theList = List(1, 2, 3, 4, 5)
theList should contain allOf(5, 3, 1) // passes
但是,如果您已经有了包含要检查的那些元素的列表,则不清楚如何使用它。下面的代码无法编译,因为 allOf()
只接受集合元素,而不是集合,并且至少需要两个元素。
val theList = List(1, 2, 3, 4, 5)
val expected = List(5, 3, 1)
theList should contain allOf(expected) // doesn't compile
因为 Scala List
没有 containsAll()
,你甚至不能这样做:
val theList = List(1, 2, 3, 4, 5)
theList.containsAll(expected) should be(true) // doesn't compile
现在我正在做以下事情,但我对此并不满意:
for(x <- expected) {
theList should contain(x)
}
是否有更流畅/Scala-ish/标准的方式来做出这个断言?
您可以使用隐式 类 添加缺少的方法
trait AllElementsOf {
implicit class AllElementsOf[L <: GenTraversable[_]](resultOfContainWord: ResultOfContainWord[L]) {
def allElementsOf(l: L)(implicit aggregating: Aggregating[L]) = {
val list = l.toList
assume(list.size >= 2, s"Expected to see list longer than 2")
resultOfContainWord.allOf(list(0), list(1), list.drop(2):_*)
}
}
}
class AllOfListSpec extends FlatSpec with ShouldMatchers with AllElementsOf {
"list" should "contain all of another list" in {
val theList = List(1, 2, 3, 4, 5)
val expected = List(5, 3, 1)
theList should contain allElementsOf expected
}
}
更新
官方 allElementsOf 将在 scalatest 3.0