我在斯卡拉case class foo(a: Array[String], b: Map[String,Any])
我正在尝试为此进行单元测试,但在将foo元素(实际和预期)存储在数组中时,却需要执行assertEquals
。因此,最后一行使用的是assertEquals(expected.deep, actual.deep)
。
映射b正确显示,但是assertEquals尝试匹配Array a的哈希码而不是内容。错误是得到是这样的:Array(foo([Ljava.lang.string@235543a70,Map("bar" -> "bar")))
整体代码看起来像
case class Foo(a: Array[String], b: Map[String, Any])
val foo = Foo(Array("1"), Map("ss" -> 1))
val foo2 = Foo(Array("1"), Map("ss" -> 1))
org.junit.Assert.assertEquals(Array(foo).deep, Array(foo2).deep)
您建议如何进行这项工作?
scala中的案例类带有其自己的hashCode
和equals
方法,不应覆盖它们。这些实现检查内容的相等性。但它依赖于case类中使用的基于“内容”的hashCode
和equals
实现类型。
[不幸的是,Arrays
并非如此,这意味着无法使用默认的equals
方法通过内容检查数组。
最简单的解决方案是使用根据内容检查是否相等的数据收集,例如Seq
。
case class Foo(a: Seq[String], b: Map[String, Any])
val foo = Foo(Seq("1"), Map("ss" -> 1))
val foo2 = Foo(Seq("1"), Map("ss" -> 1))
org.junit.Assert.assertEquals(foo, foo2)
调用deep
在这种情况下将无济于事,因为它仅扫描并转换嵌套的Array
。
println(Array(foo, Array("should be converted and printed")))
println(Array(foo, Array("should be converted and printed")).deep)
产生
[Ljava.lang.Object;@188715b5
Array(Foo([Ljava.lang.String;@6eda5c9,Map(ss -> 1)), Array(should be converted and printed))