gpt4 book ai didi

scala - 当包含内部数组时,Scala case 类的相等性在 junit assertEquals 中不起作用

转载 作者:行者123 更新时间:2023-12-04 10:59:57 25 4
gpt4 key购买 nike

我在 Scala 中有case class foo(a: Array[String], b: Map[String,Any])我正在尝试为此运行单元测试,但 assertEquals将 foo 元素(实际和预期)存储在数组中。
所以最后一行是使用 assertEquals(expected.deep, actual.deep) .

map b 显示正确,但 assertEquals 正在尝试匹配数组 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 中的案例类有自己的 hashCodeequals不应该被覆盖的方法。此实现检查内容的相等性。但它依赖于基于“内容”的 hashCodeequals案例类中使用的类型的实现。

不幸的是,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))

关于scala - 当包含内部数组时,Scala case 类的相等性在 junit assertEquals 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com