如何使用 ScalaTest 正确测试 Try[T]?

How to test a Try[T] with ScalaTest correctly?

我有一个方法 returns 一个 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"
}

然而,检查 isSuccesstrue 看起来有点笨拙,因为对于选项和序列,有 should be(empty)shouldNot be(empty) 之类的东西。我找不到像 should be(successful).

这样的东西

这是否存在或者我的方法真的可行吗?

只需检查它是否为您的 return 值的成功类型:

maybeRes shouldBe Success("moo")

或者

import org.scalatest.TryValues._

// ... 

maybeRes.success.value should be "moo"

另一种可能性是

import org.scalatest.TryValues._
maybeRes.success.value.bar shouldBe "moo"

这将给出一条消息,指示 Try 不成功,而不是在 maybeRes.get 中抛出异常。

存在 OptionEitherPartialFunction 的模拟(使用相关导入)

I cannot find anything like should be(successful).

maybeRes must be a 'success