我有一个返回 Try
的方法目的:
def doSomething(p: SomeParam): Try[Something] = {
// code
}
我现在想用 ScalaTest 测试这个。目前我是这样做的:
"My try method" should "succeed" in {
val maybeRes = doSomething(SomeParam("foo"))
maybeRes.isSuccess shouldBe true
val res = maybeRes.get
res.bar shouldBe "moo"
}
但是检查
isSuccess
成为 true
看起来有点笨拙,因为对于 Options 和 Sequences 有类似 should be(empty)
的东西和 shouldNot be(empty)
.我找不到像 should be(successful)
这样的东西.这是否存在或者我的方法真的是要走的路?
最佳答案
另一种可能是做
import org.scalatest.TryValues._
maybeRes.success.value.bar shouldBe "moo"
这将给出一条消息,指示
Try
没有成功,而不是在 maybeRes.get
中抛出异常.模拟存在于
Option
, Either
和 PartialFunction
(使用相关导入)
关于scala - 如何使用 ScalaTest 正确测试 Try[T]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44112671/