I have 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
for my Seq[Data]
type:
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)