Scalatest在案例类列表中的双等价

时间:2017-02-14 21:29:54

标签: scala scalatest

我的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

2 个答案:

答案 0 :(得分:0)

你可以选择

forAll(output.zipAll(expected, null, null)) {
  case (a, b) => a.value shouldEqual b.value +- 0.25
}

使用zipAll因为zip在长度不匹配时会错误地成功,但是您通过这种方式获得的错误信息并不太好。

答案 1 :(得分:0)

我最终为我的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)