scala - 在 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) ...
我如何测试这个捕捉错误?确实应该通过这个测试...
解决方案
你在 Scala 中你不应该抛出异常,但在 scalatest 你可以做这样的事情:
a[yourException.type] should be thrownBy yourFunction()
你可以做一个更好的版本,
case class Error(exception: Exception){
throw exception
???
}
或者类似的东西
case object Error
然后你像这样检查它:
Error shouldBe yourFunction()
推荐阅读
- python - 根据单词之间的数字范围选择字符串
- time-complexity - 我用来查找时间复杂度的方法是否正确?
- java - 使用不进化的遗传算法重建图像
- flutter - 如果我改变频道,我应该调试所有东西吗?
- python - 如何使用分类 sklearn boston 住房数据集使用 matplotlib 绘制线性图
- java - java.lang.IllegalArgumentException 与 AnnotationConfigApplicationContext
- django - 使用基于类的视图 (CBV) Django 2.1 Python 重定向页面
- reporting-services - SSRS:连接字段的不同值
- c++ - nullptr 没有打破零终止字符串的循环
- python - 使用 Python 在 Heroku 上入门时遇到问题