How to validate Try [T] using ScalaTest?

I have a method that returns an object Try:

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

Now I want to test this with ScalaTest. I am currently 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 isSuccessfor truelooks a bit awkward, because for options and sequences there are things like should be(empty)and shouldNot be(empty). I can not find anything like it should be(successful).

Is this or is my approach really suitable?

+2
source share
3 answers

Another opportunity is to do

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

This will give a message indicating that Tryit failed, and did not throw an exception in maybeRes.get.

Option, Either PartialFunction ( )

+6

, :

maybeRes shouldBe Success("moo")
+8

As an alternative

import org.scalatest.TryValues._

// ... 

maybeRes.success.value should be "moo"
+1
source

Source: https://habr.com/ru/post/1673344/


All Articles