在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 /标准方式来做出这个断言?
答案 0 :(得分:0)
您可以使用隐式类添加缺少的方法
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