Alternatively consider CollectionConverters
import scala.jdk.CollectionConverters._
testMap.asScala should contain allOf (1->2, 2->4, 3->6)
If we wish to maintain the following DSL
testMap should contain allOf (1->2, 2->4, 3->6)
then we could provide a custom instance of Aggregating typeclass which compares equality of Entry with Scala tuples
trait JavaMapHelpers {
def javaEntryEqualsScalaTuple[K, V]: Equality[java.util.Map.Entry[K, V]] =
(a: java.util.Map.Entry[K, V], b: Any) => b match {
case (k, v) => a.getKey == k && a.getValue == v
case _ => false
}
implicit def aggregatingNatureOfJavaMapWithScalaTuples[K, V, JMAP[k, v] <: java.util.Map[k, v]]: Aggregating[JMAP[K, V]] =
Aggregating.aggregatingNatureOfJavaMap(javaEntryEqualsScalaTuple)
def javaMap[K, V](elements: (K, V)*): java.util.LinkedHashMap[K, V] = {
val m = new java.util.LinkedHashMap[K, V]
elements.foreach(e => m.put(e._1, e._2))
m
}
}
class JavaMapSpec extends AnyFlatSpec with Matchers with JavaMapHelpers {
"Java Map" should "be checkable with Scala tuples" in {
javaMap((1,2), (2,4), (3,6)) should contain allOf (1->2, 2->4, 3->6)
}
}
Defining custom equality which compares Java Entry with Scala tuple works because under the hood containsAllOf calls entrySet on Java map and then checks with provided Equality
def containsAllOf(map: JMAP[K, V], elements: scala.collection.Seq[Any]): Boolean = {
checkAllOf(map.entrySet.asScala, elements, equality)
}