如何在ScalaTest中正确测试Try[T]



我已经检查了帖子中指定的答案如何使用ScalaTest正确测试Try[T]?

但是,如果我必须在函数调用后进行任何断言,或者如果我必须检查for { } yield { }块中的断言,那么我将遵循以下给定的方法:

def test(a: Int, b: Int): Try[Int] = Try {
a / b
}
it.should("succeed").in {
(for {
res <- test(0, 1)
} yield {
assert(res === 0)
// assume more assertions are to be made
}) match {
case Success(value)     => value
case Failure(exception) => fail(exception)
}
}
it.should("fail").in {
test(1, 0).failure.exception.getClass.mustBe(classOf[java.lang.ArithmeticException])
}

上述方法的问题是,对于成功案例,如果单元测试逻辑中发生任何问题,那么它将显示指向case Failure(exception) => fail(exception)行的错误,而不是实际错误发生的行。如果测试用例很大,那么用户将很难找到错误发生的确切位置。

那么,有没有更好的方法来对返回Try[T]的函数进行单元测试,而不将断言移动到for { } yield { }块之外?

TryValues特性(此处记录(旨在帮助实现这一点:

class MyTestSpec extends FlatSpec with Matchers with TryValues {
"tryTest" should "succeed" in {
// Normal tests
test(0, 1).isSuccess shouldBe true
test(1, 1).isFailure shouldBe true
// Use TryValues conversions
test(0, 1).success.value shouldBe 0
test(1, 1).failure.exception should have message "should be zero"
}
}

最新更新