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

2019-02-23 07:14发布

I have a method that returns a Try object:

def doSomething(p: SomeParam): Try[Something] = {
  // code
}

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"
}

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?

3条回答
时光不老,我们不散
2楼-- · 2019-02-23 07:30

Alternatively

import org.scalatest.TryValues._

// ... 

maybeRes.success.value should be "moo"
查看更多
一纸荒年 Trace。
3楼-- · 2019-02-23 07:33

Another possibility is to do

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

This will give a message indicating the Try was not a success, instead of throwing the exception in maybeRes.get.

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

查看更多
劳资没心,怎么记你
4楼-- · 2019-02-23 07:38

Just check to see that it is the success type with your return value:

maybeRes shouldBe Success("moo")
查看更多
登录 后发表回答