【问题标题】:How do I get meaningful error messages for nested scala unit equality matchers?如何为嵌套的 scala 单元相等匹配器获取有意义的错误消息?
【发布时间】: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


    【解决方案1】:

    考虑使用:

    left.array should contain theSameElementsInOrderAs other.array
    

    参考:Working with "sequences"

    【讨论】:

    • 感谢您的回复,我考虑过这个但被拒绝了,因为我的班级中有多个字段(例如 10 个),我不想为每个检查写 10 个应该语句。
    • @DreamFlasher 也许我不清楚 - 不确定。我的意思是建议用left.array should contain theSameElementsInOrderAs other.array替换left.array.length should be (other.array.length) for (i <- 0 until left.array.length) { left.array(i) should be (other.array(i)) }
    • 啊,谢谢,现在有道理了,是的,你是对的,我不应该自己比较元素,而是使用数组比较。但我仍然没有收到错误消息?
    • 我相应地改变了问题,现在更有意义了吗?
    最近更新 更多