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

编程入门 行业动态 更新时间:2024-10-19 05:30:38
本文介绍了如何使用 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.

Option、Either 和 PartialFunction 的模拟存在(使用相关导入)

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

更多推荐

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

本文发布于:2023-11-25 15:24:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630285.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   正确   测试   ScalaTest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!