gpt4 book ai didi

案例类列表中的Scalatest Double等价

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

我有 Double值将相似,但不准确。通常我会这样做:

val a: Double = ???
val b: Double = ???

a shouldEqual b +- 0.25

如果我只是比较单个案例类,我会这样做:
case class Data(label: String, value: Double)
val a: Data = ???
val b: Data = ???
a.value shouldEqual b.value +- 0.25

就我而言,我有一个案例类实例列表,并希望将它们与它们的容差进行比较 value属性:
val output = Seq(Data("a", 1.1), Data("b", 1.2))
val expected = Seq(Data("a", 0.9), Data("b", 1.1))
output should contain theSameElementsInOrderAs expected

当然,那会归档,因为 value属性不完全匹配。我需要的是这样的:
output should contain theSameElementsInOrderAs expected +- 0.25

最佳答案

我最终定义了一个自定义 Matcher我的 Seq[Data]类型:

trait CustomMatcher {

class SeqDataContainsTheSameElementsInOrderAs(expected: Seq[Data]) {

override def apply(left: Seq[Data]): MatchResult = {

// ... do other checks like comparing the length and such

val bad = left.zip(expected).filter(t => {
val difference = Math.abs(t._1.value - t._2.value)
difference > TOLERANCE // Declare this somewhere
})

// Return the MatchResult, you will probably want to give better error messages than this
MatchResult(
bad.isEmpty,
s"""Some of the values were not equal""",
s"""Everything was equal"""
)
}

def customContainTheSameElementsInOrderAs(expected: Seq[Data]) = new SeqDataContainsTheSameElementsInOrderAs(expected)
}
}

然后我像这样使用它:
output should customContainTheSameElementsInOrderAs(expected)

关于案例类列表中的Scalatest Double等价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236592/

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