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

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

For example, how can I verify 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 the lists, I can write a test like

someVal should be (10.0 +- 1.0)

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

someList should contain (3.5)

but as far as I know, there is no good way to check items in a list using a range. Sort of

someList should contain (10.0 +- 1.0)

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

+4
source share
1 answer

You can use TolerantNumerics to specify 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)
}

It will not work:

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

:

List[Double](1.5, 2.25, 3.5, 9.9) should contain(10.0)
+4

Source: https://habr.com/ru/post/1694031/


All Articles