1
votes

In ScalaTest it's easy to check whether a container has certain elements:

val theList = List(1, 2, 3, 4, 5)
theList should contain allOf(5, 3, 1) // passes

However, if you already have a list containing those elements you want to check for, it's not obvious how to make use of it. The code below doesn't compile, because allOf() only takes collection elements, not collections, and expects at least two of them.

val theList = List(1, 2, 3, 4, 5)
val expected = List(5, 3, 1)
theList should contain allOf(expected) // doesn't compile

Since a Scala List doesn't have containsAll(), you can't even do this:

val theList = List(1, 2, 3, 4, 5)
theList.containsAll(expected) should be(true) // doesn't compile

Right now I'm doing the following, but I'm not happy with it:

for(x <- expected) {
  theList should contain(x)
}

Is there a more fluent / Scala-ish / standard way to make this assertion?

1
Possible duplicate of stackoverflow.com/questions/26801679/…edi

1 Answers

0
votes

You can use implicit classes to add missing method

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
  }
}

Update

Official allElementsOf will be in scalatest 3.0