首页 > 解决方案 > 在 Scala 中测试异常

问题描述

我想测试(在 Intellij Idea 测试框架中)以下代码:

def eval(t: Term): Term = t match {
    case t if isVal(t) => t
    case If(t1,t2,t3) if True == eval(t1) => eval(t2)
    case If(t1,t2,t3) if False == eval(t1) => eval(t3)
    case Succ(t) if isNum(eval(t)) => Succ(eval(t))
    case Pred(t) => eval(t) match {
      case Zero => Zero
      case Succ(v) if isNum(v) => v
      case _ => throw TermIsStuck(Pred(eval(t)))
    }
    case IsZero(t) => eval(t) match {
      case Zero => True
      case Succ(v) if isNum(v) =>False
      case _ => throw TermIsStuck(IsZero(eval(t)))
    }
    case _ => throw TermIsStuck(t)
  }

作为参考,您可以查看此存储库。所以我写了以下测试:

 test("testEval") {

    Arithmetic.term(new Arithmetic.lexical.Scanner("if iszero pred pred 2 then if iszero 0 then true else false else false")) match {
      case Arithmetic.Success(res,next) => assert(eval(res) == True)
      case Arithmetic.Failure(msg,next) => assert(false)
    }

    Arithmetic.term(new Arithmetic.lexical.Scanner("pred succ succ succ false")) match {
      case Arithmetic.Success(res,next) => assert(Arithmetic.eval(res) == TermIsStuck(Succ(False)))
      case Arithmetic.Failure(msg,next) => assert(false)
    }

  }

得到错误:

成功(假)

fos.Arithmetic$TermIsStuck: Succ(False) ...

我如何测试这个捕捉错误?确实应该通过这个测试...

标签: scalatesting

解决方案


你在 Scala 中你不应该抛出异常,但在 scalatest 你可以做这样的事情:

a[yourException.type] should be thrownBy yourFunction()

你可以做一个更好的版本,

case class Error(exception: Exception){

throw exception

???

}

或者类似的东西

case object Error

然后你像这样检查它:

Error shouldBe yourFunction() 

推荐阅读