Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 420
rabejens Avatar asked May 22 '17 12:05

rabejens


People also ask

How do you ignore a test in ScalaTest?

It has been inserted into Scaladoc by pretending it is a trait. When you mark a test class with a tag annotation, ScalaTest will mark each test defined in that class with that tag. Thus, marking the SetSpec in the above example with the @Ignore tag annotation means that both tests in the class will be ignored.

What is a fixture in ScalaTest?

Regarding to the ScalaTest documentation: A test fixture is composed of the objects and other artifacts (files, sockets, database connections, etc.) tests use to do their work. When multiple tests need to work with the same fixtures, it is important to try and avoid duplicating the fixture code across those tests.


3 Answers

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)

like image 90
Cyrille Corpet Avatar answered Oct 23 '22 17:10

Cyrille Corpet


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

maybeRes shouldBe Success("moo")
like image 30
Matt Fowler Avatar answered Oct 23 '22 18:10

Matt Fowler


Alternatively

import org.scalatest.TryValues._

// ... 

maybeRes.success.value should be "moo"
like image 36
Gabriele Petronella Avatar answered Oct 23 '22 17:10

Gabriele Petronella