如何检查 Failure[T] 中包含哪个异常?
How to check which exception is contained in a Failure[T]?
我想知道使用 ScalaTest 检查失败 Try
内容的最佳方法。我现在正在做的是这样的:
"Subject" should "throw proper exceptions.." in {
a[IllegalArgumentException] should be thrownBy {
val tryValue = // some method call..
if (tryValue.isFailure) throw tryValue.failed.get
}
}
如你所见,我只是解开异常并手动抛出它。有没有更惯用的方法来实现同样的事情?
希望对您有所帮助
Try(1 / 0) match {
case Success(success) =>
case Failure(error) => println(error.getClass.getName)
}
结果: java.lang.ArithmeticException
我会选择不会真正抛出异常的东西,因为 Failure
结果只是另一个可以匹配的结果:
"Subject" should "throw proper exceptions.." in {
val tryValue = // some method call...
tryValue shouldBe a[Failure[_]]
tryValue.failed.get shouldBe an[IllegalArgumentException]
}
以上将断言分开:对于未发生故障的情况和发生错误故障的情况,您会看到不同的测试失败。
我想知道使用 ScalaTest 检查失败 Try
内容的最佳方法。我现在正在做的是这样的:
"Subject" should "throw proper exceptions.." in {
a[IllegalArgumentException] should be thrownBy {
val tryValue = // some method call..
if (tryValue.isFailure) throw tryValue.failed.get
}
}
如你所见,我只是解开异常并手动抛出它。有没有更惯用的方法来实现同样的事情?
希望对您有所帮助
Try(1 / 0) match {
case Success(success) =>
case Failure(error) => println(error.getClass.getName)
}
结果: java.lang.ArithmeticException
我会选择不会真正抛出异常的东西,因为 Failure
结果只是另一个可以匹配的结果:
"Subject" should "throw proper exceptions.." in {
val tryValue = // some method call...
tryValue shouldBe a[Failure[_]]
tryValue.failed.get shouldBe an[IllegalArgumentException]
}
以上将断言分开:对于未发生故障的情况和发生错误故障的情况,您会看到不同的测试失败。