Let's say I have a function that returns a array of doubles. I want to test this function and have calculated the correct value by hand. However since it's floating point numbers, I can't do direct comparisons so is there any sweet syntax by ScalaTest that makes me able to compare double arrays with an epsilion/error margin?
Thanks
Well as I feared there is no nice syntax in ScalaTest for this, and I will accept my own answer with a very basic solution.
val Eps = 1e-3 // Our epsilon
val res = testObject.test // Result you want to test.
val expected = Array(...) // Expected returning value.
res.size should be (expected.size)
for (i <- 0 until res.size) res(i) should be (expected(i) +- Eps)
As seen, this works. Then you can make it nicer by perhaps defining an implicit method.
How about:
import Inspectors._
import scala.math._
forExactly(max(a1.size, a2.size), a1.zip(a2)){case (x, y) => x shouldBe (y +- eps)}
Or you can provide custom equality (there is a built-in one as @Suma sugested)
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