Comparing collection contents with ScalaTest

Michael Koval picture Michael Koval · Sep 15, 2011 · Viewed 26.6k times · Source

I'm trying to unit-test some Scala that is very collection-heavy. These collections are returned as Iterable[T], so I am interested in the contents of the collection, even if the underlying types differ. This is actually two related problems:

  1. How do I assert that two ordered collections contain the same sequence of elements?
  2. How do I assert that two unordered collections contain the same set of elements?

In summary, I'm looking the Scala-equivalent of NUnit's CollectionAssert.AreEqual (ordered) and CollectionAssert.AreEquivalent (unordered) in ScalaTest:

Set(1, 2) should equal (List(1, 2))          // ordered, pass
Iterable(2, 1) should equal (Iterable(1, 2)) // unordered, pass

Answer

Christoph Dittberner picture Christoph Dittberner · Jun 16, 2014

Meanwhile you can use

Iterable(2, 1) should contain theSameElementsAs Iterable(1, 2)

To test the ordered set you have to convert it to a sequence.

Set(1, 2).toSeq should contain theSameElementsInOrderAs List(1, 2)