gpt4 book ai didi

ScalaTest 深度对比最佳实践

转载 作者:行者123 更新时间:2023-12-04 17:55:16 24 4
gpt4 key购买 nike

我正在尝试为返回包含数组的类的元组的函数编写单元测试。

一个简单的assert(out === expectedOut)out should be(expectedOut)由于 Array,不比较 LHS 和 RHS 上的类的内容。在 ScalaTest 中有没有一种巧妙的方法可以做到这一点?

我看过自定义匹配器,但我不确定这是否是我想要做的最好的方法。因此,任何来自专家经验的信息都将不胜感激。

编辑:
这是一个似乎并非如此的情况:

object Utils {
case class Product(id: Int, prices: Array[Int])


def getProductInfo(id: Int, prices: Array[Int]): Option[Product] = {
val sortedPrices = prices.sortWith(_ < _)
Some(Product(id, sortedPrices))
}
}

---

import org.scalatest._
import Utils._

class DataProcessorSpec extends FlatSpec with Matchers with OptionValues {
val id = 12345
val priceList = Array(10,20,30)

val prod = Utils.getProductInfo(id, priceList)
val expectedProd = Some(Utils.Product(id, priceList))

"A DataProcessorSpec" should "return the correct product information" in {
prod should be(expectedProd)
}
}

测试失败,因为 sortWith据我所知,导致创建一个新数组并因此指向不同的内存位置。

最佳答案

更新 :使用代码示例,这更清楚:

比较失败,因为 shoud be使用案例类的 equals函数来执行比较,并且案例类不会“深入”比较数组 - 这意味着,正如您所怀疑的那样,不同的实例将不相等(请参阅更多信息 here )。

解决方法 :

  • 分别验证案例类的每个“部分”的相等性:
    prod.get.prices should be(expectedProd.get.prices)
    prod.get.id should be(expectedProd.get.id)
  • 如果使用 Array不是必须的,您可以更改案例类以使用 Seq[Int] ,这将使测试通过,因为 Seq的实现 equals是“深”

  • 比较数组 :

    当“单独”比较时,匹配器的 should be 按预期(“深入”)比较数组。 :
    arr1 should be(arr2) // true if contents is the same

    如果只是想比较内容,不验证 out确实是 Array ,您可以使用 theSameElementsInOrderAs :
    arr1 should contain theSameElementsInOrderAs arr2

    关于ScalaTest 深度对比最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36449703/

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