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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With