I was looking for a ScalaTest matcher to check that a list contains all of the needed elements (given within another list), but that may also be others.
contain allOf
demands to get two fixed elements, for some reason, the rest as varargs.
I can do a workaround like this, but it's tremendously ugly:
val list = List(1,2,3,4)
val wanted = List(1,2,3)
list should contain allOf ( wanted.head, wanted.tail.head, wanted.tail.tail :_* ) // ugly workaround
For giving a list as the match, there is contain theSameElementsAs
. However, it does not allow extraneous elements to be in the probed value (I think).
So:
- am I missing something?
- why is
allOf
declared in the way that it must be given two fixed elements in the front (i.e. why not just pass varargs?) - should there be
theSameElementsAndMaybeMoreThan
method (presumably with a better name)?
Some code I tried with:
val list = List.empty[String]
//list should contain allOf("a") // does not compile
list should contain allOf("a","b")
list should contain allOf("a","b","c")
val wanted = List("a","b","c")
//list should contain allOf( wanted ) // does not compile
list should contain allOf( wanted.head, wanted.tail ) // compiles, but tests the wrong thing; against List(head,List(tail))
Scala 2.11.4, ScalaTest 2.2.1
Edit:
I probably end up using something like:
wanted.foreach( list should contain(_) )
However, this does not seem as readable to me (the should
is kind of embedded) as the built-in collection constructs.
Set(1, 4).subsetOf(Set(1, 2, 3, 4, 5))
– Anas AlkhatiballOf
anymore, it will be justcontain
. – Nader Ghanbariassert
instead ofshould
matchers, right? I'd like to use matchers for the tests. – akauppi