Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 638
M.K. Avatar asked Jan 07 '15 00:01

M.K.


People also ask

Should VS must ScalaTest?

should and must are the same semantically. But it's not about better documentation, it's basically just down to personal stylistic preference (I prefer must for example).

What is FlatSpec in Scala?

5.1. The main premise behind the FlatSpec trait is to help facilitate a BDD style of development. It's named flat because the structure of the tests we write is unnested in nature. In addition, this trait tries to guide us into writing more focused tests with descriptive, specification-style names.

What is Instanceof in Scala?

You can use the isInstanceOf method to test the type of an object: if (x. isInstanceOf[Foo]) { do something ... However, some programmers discourage this approach, and in other cases, it may not be convenient. In these instances, you can handle the different expected types in a match expression.


1 Answers

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)
like image 112
Spiro Michaylov Avatar answered Sep 18 '22 00:09

Spiro Michaylov