【发布时间】:2023-10-11 17:01:02
【问题描述】:
我想在包含数组的案例类的 ScalaTest 中断言相等。 (因此,case 类的内置相等匹配器不适用。) 示例:
case class Example(array: Array[Double], variable: Integer)
测试存根:
val a = Example(Array(0.1, 0.2), 1)
val b = Example(Array(0.1, 0.2), 1)
a should equal (b)
按预期失败。所以我实现了一个平等特征:
implicit val exampleEq =
new Equality[Example] {
def areEqual(left: Example, right: Any): Boolean =
right match {
case other: Example => {
left.array should contain theSameElementsInOrderAs other.array
left.variable should be other.variable
true
}
case _ => false
}
}
哪个有效。另一种选择是在“应该”的所有地方用 == 实现平等特征,如果在一个地方为假,则返回假,否则返回真。两者的问题是,在运行测试时,我收到两个“示例”对象不相等的错误消息(如果它们不相等),但我想看看它们在哪个元素中不同。
我如何做到这一点?
感谢您的帮助!
[更新]在实践中示例包含多个数组和其他字段,我相应地更改了代码。
【问题讨论】:
标签: scala equality scalatest matcher