How to use ScalaTest “contain allOf” on two lists?

泪湿孤枕 提交于 2019-12-01 15:37:34

Bill Venners had this to say on the ScalaTest mailing list:

Yes, we didn't want to hold up the 2.0 release to add that, but have since added it. I believe we added it to master, though, not the 2.2.x branch. Regardless, the syntax looks like:

xSet should contain allElementsOf (ySet)

Link to the message.

I don't think there's any good reason for this. You can remedy this with a pimp my class:

object ScalaTestUtils {
    import org.scalatest.words.ResultOfContainWord

    implicit class ResultOfContainWordImprovements[T](val contains: ResultOfContainWord[Seq[T]]) {
        def allOf(right: Seq[T]) = contains allOf(right.head, right.tail.head, right.tail.tail :_*)
    }
}

You should probably make this account for Seqs with fewer than 2 elements (for which this would fail).

Then, you can do:

import ScalaTestUtils._
Seq(1, 2, 3) should contain allOf Seq(1, 2)

Another possible solution is:

import org.scalatest.Inspectors.forAll

forAll(list) { wanted should contain(_) }

Expect an error message similar to this:

scala> forAll(List(1, 2)) { List(1) should contain(_) }
org.scalatest.exceptions.TestFailedException: forAll failed, because:
  at index 1, List(1) did not contain element 2 (<console>:18)
in List(1, 2)
...
Caused by: org.scalatest.exceptions.TestFailedException: List(1) did not contain element 2
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!