如何使用 ScalaTest 正确测试 Try[T]? [英] How to test a Try[T] with ScalaTest correctly?

查看:84
本文介绍了如何使用 ScalaTest 正确测试 Try[T]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 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.

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

The analog exist for Option, Either and PartialFunction (using the relevant import)

这篇关于如何使用 ScalaTest 正确测试 Try[T]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆