我想检查两个Traversable
是否包含相同的元素而不考虑它们的顺序。
所以,我自己尝试了,并编写了以下简单示例:
implicit val l = 3
implicit def equality(implicit l: Int) = new Equality[String] {
override def areEqual(a: String, b: Any): Boolean = (a, b) match {
case (_, b: Int) => a.toInt == b
}
}
"Test" should "check how equality works" in {
List("1") should contain theSameElementsAs Vector(1) //Fine
List("1", "2") should contain theSameElementsAs Vector(1, 2) //Fine
List("1", "2", "3") should contain theSameElementsAs Vector(1, 2, 3) //Fine
List("1", "2", "2") should contain theSameElementsAs Vector(1, 2, 2) //Error
List("2", "1") should contain theSameElementsAs Vector(1, 2) //Error
}
正如the documentation所说:
"
contain theSameElementsAs
"语法让你断言那两个 聚合包含相同的对象
它不应该考虑重复和顺序。那有什么不对?
答案 0 :(得分:1)
我认为根本问题在于equality
关系并不像人们所期望的那样具有反思性。那是x == y
然后是y == x
。
Scalacheck使用提供的equality
函数尝试在目标集合中count the number of repetitions。
遇到equality(2,2)
,tryEquality
fails internally with a ClassCastException
时,将比较默认为false。
底线:Equality
需要反思(如同旧的数学要求)才能获得预期的结果。
答案 1 :(得分:0)
在左侧使用Int
列表而不是字符串列表。
"Test" should "check how equality works" in {
List(1) should contain theSameElementsAs Vector(1) //Fine
List(1, 2) should contain theSameElementsAs Vector(1, 2) //Fine
List(1, 2, 3) should contain theSameElementsAs Vector(1, 2, 3) //Fine
List(1, 2, 2) should contain theSameElementsAs Vector(1, 2, 2) //Fine
List(2, 1) should contain theSameElementsAs Vector(1, 2) //Fine
}
输出:
[info] Test
[info] - should check how equality works
[info] Run completed in 354 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.