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

4

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?

Largo answered 22/5, 2017 at 12:18 Comment(0)
P
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)

Pirtle answered 22/5, 2017 at 13:55 Comment(4)
This was what I really looked for - testing for success and getting the result object (which is not only a string in my real code) for further tests.Largo
Glad I could help. I find this really helpful, since you can use it for different error handling contexts.Pirtle
How to check for failure?Manilla
maybeRes.failure.exception should have message "/ by zero", see the scaladocPirtle
A
12

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

maybeRes shouldBe Success("moo")
Anastassia answered 22/5, 2017 at 12:28 Comment(3)
@Largo 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.Trapezius
@Trapezius that's why I marked Cyrille Corpet's answer as the correct one.Largo
Unfortunate that scalatest doesn't support this as the best answer. Clearly this is a simpler semantic than dealing with TryValues.Lipo
C
2

Alternatively

import org.scalatest.TryValues._

// ... 

maybeRes.success.value should be "moo"
Carrousel answered 22/5, 2017 at 13:50 Comment(0)
S
1

I cannot find anything like should be(successful).

maybeRes must be a 'success
Satiny answered 29/4, 2022 at 2:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.