最新的检查除以0(例外)

时间:2014-01-24 08:52:30

标签: 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
   * @return called quotient and it calculates how many times can we divide numerator by denominator
   */
  def divide(numerator: Double, denominator: Double): Double = denominator / numerator
}

显示denominatornumerator已切换。我想用带有org.scalatest.WordSpecLike样式和DSL org.scalatest.MustMatchers的scalatest框架编写单元测试。最后,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框架中检查/测试infinity /除以0?

谢谢!

最佳

1 个答案:

答案 0 :(得分:2)

对于例外情况,您通常使用intercept。这说“我希望函数在给定的场景中抛出一个特定的异常”。简而言之,如果抛出异常,测试将通过。

scenario("whatever") {
  val err = intercept[ArithmeticException] {
    callTheFunctionWithTheException
  }
  err.getMessage shouldEqual "somemessage"
}