如何使用 ScalaTest 正确测试 Try[T]? [英] How to test a Try[T] with ScalaTest correctly?
问题描述
我有一个返回 Try
对象的方法:
I have a method that returns a Try
object:
def doSomething(p: SomeParam): Try[Something] = {
// code
}
我现在想用 ScalaTest 测试这个.目前我是这样做的:
I now want to test this with ScalaTest. Currently I am doing it like this:
"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)
和不应该是(空)
.我找不到像 should be(successful)
这样的东西.
However checking for isSuccess
to be true
looks a bit clumsy because for Options and Sequences there are things like should be(empty)
and shouldNot be(empty)
. I cannot find anything like should be(successful)
.
这是否存在或者我的方法真的是要走的路?
Does this exist or is my approach really the way to go?
推荐答案
另一种可能是做
import org.scalatest.TryValues._
maybeRes.success.value.bar shouldBe "moo"
这将给出一条消息,表明 Try
没有成功,而不是在 maybeRes.get
中抛出异常.
This will give a message indicating the Try
was not a success, instead of throwing the exception in maybeRes.get
.
Option
、Either
和 PartialFunction
的模拟存在(使用相关导入)
The analog exist for Option
, Either
and PartialFunction
(using the relevant import)
这篇关于如何使用 ScalaTest 正确测试 Try[T]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!