2017-02-14 60 views
2

我有Double值在价值上相似,但不是确切的。通常情况下,我会做:Scalatest案例类别清单中的双等同案件

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 

在我的情况,我有case类实例的列表,并想用比较宽容他们的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 

回答

0

我结束了定义自定义MatcherSeq[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) 
0

你可以只去

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

使用zipAll因为zip会错误地成功时的长度不匹配,但错误信息你会得到这样ISN太不好。