Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScalaTest: check for contents of a sequence with ShouldMatcher

In my unit test, I want to express that a computed (result) sequence yielded a predefined sequence of result values. But without assuming anything about the actual implementation type of the sequence container.

And I want to spell out my intent rather clear and self-explanatory.
If I try to use the "ShouldMatchers" of ScalaTest and write

val Input22 = ...
calculation(Input22) should equal (Seq("x","u"))

...then I get into trouble with the simple equality, because calculation(..) might return an ArrayBuffer, while Seq("x","u") is an List

like image 656
Ichthyo Avatar asked Sep 11 '10 14:09

Ichthyo


1 Answers

Are you using 2.7.7? In 2.8 different Seq's with the equal elements (in the same order) should be equal:

scala> import org.scalatest.matchers.ShouldMatchers._
import org.scalatest.matchers.ShouldMatchers._

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val list = List(1, 2, 3)
list: List[Int] = List(1, 2, 3)

scala> val arrayBuffer = ArrayBuffer(1, 2, 3)
arrayBuffer: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

scala> list == arrayBuffer
res2: Boolean = true

scala> arrayBuffer == list
res3: Boolean = true

scala> list should equal (arrayBuffer)

scala> arrayBuffer should equal (list)

The one exception to this rule in 2.8 is arrays, which can only be equal to other arrays, because they are Java arrays. (Java arrays are not compared structurally when you call .equals on them, but ScalaTest matchers does do structural equality on two arrays.)

like image 163
Bill Venners Avatar answered Oct 23 '22 04:10

Bill Venners