Scala 缩放测试检查除以0(异常)
我有一个简单的Scala除法函数,如:Scala 缩放测试检查除以0(异常),scala,testing,scalatest,Scala,Testing,Scalatest,我有一个简单的Scala除法函数,如: class ScalaFunction { /** * This is simple mathematics division function. Example: numerator = 20 and denominator = 4 equals 5 (result). * @param numerator also called dividend * @param denominator also called divisor
class ScalaFunction {
/**
* This is simple mathematics division function. Example: numerator = 20 and denominator = 4 equals 5 (result).
* @param numerator also called dividend
* @param denominator also called divisor
* @return called quotient and it calculates how many times can we divide numerator by denominator
*/
def divide(numerator: Double, denominator: Double): Double = denominator / numerator
}
显然,分母
和分子
是切换的。我想用scalatest框架编写单元测试,使用org.scalatest.WordSpecLike
样式和DSLorg.scalatest.MustMatchers
。最后,Scala Spec类应该如下所示:
class ScalaFunctionSpec extends WordSpecLike with MustMatchers {
"A division function" when {
val scalaFunction = new ScalaFunction()
"divide 7 by 0" must {
"result in exception or infinity" in {
// how to check for infinity or division by 0?
// scalaFunction.divide(7, 0) must equal(?inf?)
}
}
}
}
如何在scalatest框架中检查/测试无穷大/除以0
谢谢
最佳对于您通常使用的异常拦截。这表示“我希望函数在给定场景中抛出特定异常”。简而言之,如果抛出异常,测试将通过
scenario("whatever") {
val err = intercept[ArithmeticException] {
callTheFunctionWithTheException
}
err.getMessage shouldEqual "somemessage"
}
如果您只想与
无穷大
进行比较,可以使用。在浮点除零的情况下,不会出现异常。当整数除以0时,您将得到/乘零
算术异常
。intercept实际上返回异常,因此如果需要,可以测试其他属性。