首页 > 解决方案 > scala中的数组断言

问题描述

我试图断言条件但出现错误。

我有类型为 Either[CaseClass[Array[String]]] 的结果,其值为:Right(CaseClass(Array("value")))

当我做 :


result should equal(Right(CaseClass(Array("value"))))


它给了我:


Right(CaseClass([Ljava.lang.String;@6ed4e733) did not equal Right(CaseClass([Ljava.lang.String;@43553bf0))

标签: scalascalatest

解决方案


Array不是真正的 Scala 集合并且行为不同,例如

List(42) == List(42)    // true
Array(42) == Array(42)  // false

我们看到数组在结构上没有比较。现在 ScalaTest 确实提供了特殊处理,Array确实可以在结构上比较它们

Array("") should equal (Array(""))            // pass

Array但是当嵌套在另一个容器中时它不起作用

case class Foo(a: Array[String])
Foo(Array("")) should equal (Foo(Array("")))  // fail

真正的 Scala 集合,例如List,不会遇到这个问题

case class Bar(a: List[String])
Bar(List("")) should equal (Bar(List("")))    // pass

There is an open issue Matchers fail to understand Array equality for Arrays wrapped inside a container/collection #491 to address deep equality checks for Array however for now I would suggest switching to List instead of Array. Another options is to provide your own custom equality designed to handle your specific case.


推荐阅读