Search code examples
scalaspecs2scala-java-interop

specs2 containTheSameElementsAs does not work when parameter is java.util.List


What do I need to do to pass in containTheSameElementsAs as the argument for a java.util.List parameter

For example:

 class Foo() {
   void javaList(List<Bar> bars) = ???
 }

Running a specs2 SpecificationWithJunit Test with the following code:

 val foo = mock[Foo]
 ...
 got {
    one(foo).javaList(containTheSameElementsAs(SOME_LIST))
 }

Right now I'm getting the error:

found : org.specs2.matcher.Matcher[Traversable[Bar]]

required: java.util.List[Bar]


Solution

  • You need to "adapt" the matcher to become a Matcher[java.util.List[Bar]], like this:

    import scala.collection.JavaConversions._
    
    class Foo {
      def javaList(bars: java.util.List[Int]) = bars
    }
    
    val foo = mock[Foo]
    
    foo.javaList(java.util.Arrays.asList(1, 2))
    
    got {
       one(foo).javaList(containTheSameElementsAs(Seq(1, 2)) ^^ ((_: java.util.List[Int]).toList))
    }
    

    The ((_: java.util.List[Int]).toList) part transforms the matcher argument so that it has the type expected by the matcher.