Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

scala - Handling Doubles in ScalaTest

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...