【发布时间】:2020-06-04 10:39:35
【问题描述】:
我已经检查了帖子中指定的答案 How to test a Try[T] with ScalaTest correctly?
但是,如果我必须在函数调用之后进行任何断言,或者如果我必须检查 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 { } 块之外?
【问题讨论】:
标签: scala unit-testing scalatest