specs2测试:如何获取异常完整堆栈及优化非抛出断言写法
Specs2测试:获取完整异常堆栈及断言无异常的最优写法
问题描述
我编写了如下Specs2测试代码:
import org.specs2.mutable.Specification import scala.util.Try class Tests extends Specification { def foo(): Unit = throw new Exception("oops") "test" should { "not throw an error" in { Try(foo()) must beSuccessfulTry } } } specs2.run(new Tests)
测试失败时输出如下:
[info] test should [error] x not throw an error [error] Got the exception java.lang.Exception: oops (main.scala:11)
输出未包含抛出异常的完整堆栈跟踪,增加了问题排查难度。另外,使用not(throwA(...))断言时,若目标方法抛出异常,错误报告仅显示匹配失败的堆栈,而非原异常堆栈。
请问:
- 如何获取原异常的完整堆栈跟踪?
- 是否有更优写法断言某方法不会抛出异常?
解决方案
1. 获取原异常的完整堆栈跟踪
Specs2默认会截断异常堆栈以简化输出,要显示完整堆栈,有两种实现方式:
全局配置:在项目的
specs2.conf文件中添加以下配置,全局开启完整堆栈输出:specs2.stacktrace.full = true单测试临时开启:如果仅需针对特定测试用例显示完整堆栈,可在断言后调用
showStacktrace方法:"not throw an error" in { Try(foo()) must beSuccessfulTry.showStacktrace }配置后,测试失败时会打印异常的完整堆栈,便于定位问题。
2. 断言方法不抛出异常的更优写法
推荐写法:类型安全的not(throwAn[Exception])
结合上述完整堆栈配置后,not(throwAn[Exception])是更直观的写法。Specs2提供的throwAn是类型安全版本,比throwA更清晰:
"not throw an error" in { foo() must not(throwAn[Exception]) }
测试失败时会输出原异常的完整堆栈信息。
简洁写法:beOk断言
如果不需要指定异常类型,可使用beOk断言验证代码块执行成功且无异常:
"not throw an error" in { foo() must beOk }
这种写法更简洁,同样在配置完整堆栈后能输出原异常的详细信息。
内容的提问来源于stack exchange,提问作者Thayne
相关产品推荐
相关产品推荐

