我想知道Try使用ScalaTest 检查失败内容的最佳方法。我目前正在做的事情看起来像这样:
"Subject" should "throw proper exceptions.." in {
a[IllegalArgumentException] should be thrownBy {
val tryValue = // some method call..
if (tryValue.isFailure) throw tryValue.failed.get
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我只是打开了异常并手动将其抛出。是否有更惯用的方式来实现同一目标?
考虑到结果只是可以匹配的另一个结果,我会选择不会真正引发异常的东西Failure:
"Subject" should "throw proper exceptions.." in {
val tryValue = // some method call...
tryValue shouldBe a[Failure[_]]
tryValue.failed.get shouldBe an[IllegalArgumentException]
}
Run Code Online (Sandbox Code Playgroud)
上面的内容将断言分开:对于没有失败的情况和发生错误的错误的情况,您将看到不同的测试失败。