While writing tests for operations with floats or objects containing floats (like vectors or matrices), I often want to test not for equality, but for "almost equal" (difference allowed to be some epsilon).
When using ScalaTest FunSuite, one normally writes assert(xxx == yyy)
. With floats and likes I can write assert(math.abs(xxx - yyy)<epsilon)
, but then I do not get the nice feature of the ScalaTest assert macro of being reported the compared values as a part of the failure message.
How can I perform testing of float "almost equality" in ScalaTest, so that when the test fails, the values are written as a part of the failure message?
Test example:
import org.scalatest.FunSuite
class FloatTest extends FunSuite {
test("Testing computations") {
import math._
assert(sin(Pi/4)==sqrt(0.5))
assert(sin(Pi)==0)
}
}
It can be done using TolerantNumerics and using ===
instead of ==
.
import org.scalactic.TolerantNumerics
import org.scalatest.FunSuite
class FloatTest extends FunSuite {
val epsilon = 1e-4f
implicit val doubleEq = TolerantNumerics.tolerantDoubleEquality(epsilon)
test("Testing computations") {
import math._
assert(sin(Pi / 4) === sqrt(0.5))
assert(sin(Pi) === 0.0)
}
}
For your own types you can define your own subclasses of Equality[T].
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