这是使用 KotlinTest 1.3.5 的测试代码。
val expect = 0.1
val actual: Double = getSomeDoubleValue()
actual shouldBe expect
并且在运行代码时打印了此警告。
[WARN] When comparing doubles consider using tolerance, eg: a shouldBe b plusOrMinus c
在这种情况下,我不想使用
plusOrMinus
.所以,我将代码固定为
val expect = 0.1
val actual: Double = getSomeDoubleValue()
actual shouldBe exactly(expect)
现在,没有警告。
但是,我想知道
shouldBe
之间的区别和 shouldBe exactly
.它是什么?
最佳答案
根据current sources :
infix fun Double.shouldBe(other: Double): Unit = ToleranceMatcher(other, 0.0).test(this)
哪里
ToleranceMatcher
是class ToleranceMatcher(val expected: Double, val tolerance: Double) : Matcher<Double> {
override fun test(value: Double) {
if (tolerance == 0.0)
println("[WARN] When comparing doubles consider using tolerance, eg: a shouldBe b plusOrMinus c")
val diff = Math.abs(value - expected)
if (diff > tolerance)
throw AssertionError("$value is not equal to $expected")
}
infix fun plusOrMinus(tolerance: Double): ToleranceMatcher = ToleranceMatcher(expected, tolerance)
}
所以,匹配
d shouldBe e
将完全没有任何容差地比较 double ( a - b
will never give 0
for different doubles )并打印警告:[WARN] When comparing doubles consider using tolerance, eg: a shouldBe b plusOrMinus c
而
exactly(d)
is defined asfun exactly(d: Double): Matcher<Double> = object : Matcher<Double> {
override fun test(value: Double) {
if (value != d)
throw AssertionError("$value is not equal to expected value $d")
}
}
所以它会做同样的事情 ,虽然没有任何警告。
我想,这个警告的意思是鼓励开发人员明确指定精确比较 double ,或者指定容差,因为即使以不同顺序完成的相同算术也可能会产生不同的 double 结果。
关于kotlin - 在 KotlinTest 中应该和应该完全正确有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40609834/