Handling Doubles in ScalaTest

混江龙づ霸主 提交于 2019-12-18 07:44:26

问题


I have just started using ScalaTest and I am using the following to compare two Doubles in my spec as follows:

  it should "calculate the price" in {
    val x = new X(10,10,12,1000)
    assert(x.price() === 185.92)
  }

The spec is passing even though I have put in a wrong value of 185.92 to compare against what the price function is returning (that actually returns 10.23 for the case above). I have other specs where I just compare Ints and they work as expected. But the ones involving Doubles are passing regardless. Is there another functions besides assert I should be using to compare Doubles?

EDIT:

def price () : Double

回答1:


It looks to me like you've got an implicit instance of Equality[Double] in scope along the lines of org.scalactic.TolerantNumerics, for which the documentation is here.

The example from the doc is:

implicit val doubleEquality = TolerantNumerics.tolerantDoubleEquality(0.01)

But it looks like somebody has instantiated it with a really big tolerance value in your case.

You may also consider trying explicit tolerance by using +-:

assert(x.price() === 185.92 +- 0.01)



回答2:


You can simply do actual shouldBe (expected +- tolerance) if using FlatSpec; other specs have similar matchers instead of shouldBe. It gives better messages in case of failures than assert, and the code is consistent with the other tests.



来源:https://stackoverflow.com/questions/27809423/handling-doubles-in-scalatest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!