How to call assertEquals with Double Epsilon/Precision in Kotlin?
I have figured it out!
This is how it's done
import org.junit.*
import Kotlin.Test.assertEquals
Assert.assertEquals(expected, actual, precision) // to use the jUnit standard one
assertEquals(expected, actual, message) // to use the Kotlin one
I couldn't find one, so I created my own set of functions:
import java.math.BigDecimal
import kotlin.math.abs
import kotlin.test.asserter
internal fun assertEquals(expected: Double, actual: Double?, epsilon: Double, message: String? = null) {
asserter.assertNotNull(null, actual)
asserter.assertTrue({ messagePrefix(message) + "Expected <$expected>, actual <$actual>, should differ no more than <$epsilon>." },
abs(expected - actual!!) <= epsilon)
}
internal fun assertEquals(expected: BigDecimal, actual: BigDecimal?, epsilon: Double, message: String? = null) {
asserter.assertNotNull(null, actual)
asserter.assertTrue({ messagePrefix(message) + "Expected <$expected>, actual <$actual>, should differ no more than <$epsilon>." },
(expected - actual!!).abs().toDouble() <= epsilon)
}
internal fun assertEquals(expected: Double, actual: BigDecimal?, epsilon: Double, message: String? = null) {
asserter.assertNotNull(null, actual)
asserter.assertTrue({ messagePrefix(message) + "Expected <$expected>, actual <$actual>, should differ no more than <$epsilon>." },
abs(expected - actual!!.toDouble()) <= epsilon)
}
internal fun messagePrefix(message: String?) = if (message == null) "" else "$message. "