Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a Scalatest test to match the values in a list against a range?

How could I write a test using Scalatest to see if a list contains a double within a given range?

For example, how could I check that the following list has an element that is approximately 10?

val myList = List(1.5, 2.25, 3.5, 9.9)

For values outside of lists, I might write a test like

someVal should be (10.0 +- 1.0)

and for lists whose values can be precisely known, I would write

someList should contain (3.5)

but as far as I know there is no good way to test items within a list using a range. Something like

someList should contain (10.0 +- 1.0)

doesn't seem to work. Any idea how I could write an elegant test to accomplish this?

like image 944
Glyoko Avatar asked Feb 23 '18 06:02

Glyoko


1 Answers

You can use TolerantNumerics to specify the double precision:

import org.scalatest.FlatSpec
import org.scalactic.TolerantNumerics
import org.scalatest.Matchers._

class MyTest extends FlatSpec {

  implicit val doubleEquality = TolerantNumerics.tolerantDoubleEquality(0.1)

    9.9d should be(10.0 +- 1.0)
    List[Double](1.5, 2.25, 3.5, 9.9) should contain(10.0)
}

This would fail:

List[Double](1.5, 2.25, 3.5, 9.8) should contain(10.0)

And this should succeed:

List[Double](1.5, 2.25, 3.5, 9.9) should contain(10.0)
like image 88
Xavier Guihot Avatar answered Nov 15 '22 03:11

Xavier Guihot