15

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?

rabejens
  • 7,594
  • 11
  • 56
  • 104

4 Answers4

23

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)

Cyrille Corpet
  • 5,265
  • 1
  • 14
  • 31
12

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

maybeRes shouldBe Success("moo")
Matt Fowler
  • 2,563
  • 2
  • 15
  • 18
  • @rabejens The correct way which lets failed try errors propagate in the ScalaTest reporting pipeline is `maybeRes.success.value shouldBe "moo"`, and you get that by mixing in `TryValues`. The answer above is wrong, because there's reporting precision loss when you intentionally hide the error. – flavian May 22 '17 at 13:56
  • @flavian that's why I marked Cyrille Corpet's answer as the correct one. – rabejens May 22 '17 at 14:53
  • 1
    Unfortunate that scalatest doesn't support this as the best answer. Clearly this is a simpler semantic than dealing with TryValues. – Courtland Caldwell Apr 05 '18 at 16:33
2

Alternatively

import org.scalatest.TryValues._

// ... 

maybeRes.success.value should be "moo"
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
1

I cannot find anything like should be(successful).

maybeRes must be a 'success
Laurent
  • 107
  • 7