Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check an "Either" result in Scala Test?

I am relatively new to Scala Test, and so I consulted the documentation on how to test on Either values.

I tried to replicate the instructions like that:

import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec

class EitherTest extends AnyFlatSpec with EitherValues {
  val either: Either[Exception, Int] = Right(42)

  either.right.value should be > 1
}

This implementation does not do the trick, I get a syntax error. What did I do wrong?

Error:

Error:(9, 22) value should is not a member of Int either.right.value should be > 1 Error:(9, 29) not found: value be either.right.value should be > 1 – Hannes 14 hours ago

like image 766
Hannes Avatar asked Dec 21 '19 22:12

Hannes


People also ask

What is FlatSpec in Scala?

Trait FlatSpec is so named because your specification text and tests line up flat against the left-side indentation level, with no nesting needed. FlatSpec 's no-nesting approach contrasts with traits FunSpec and WordSpec , which use nesting to reduce duplication of specification text.

What is assert in Scala?

assert is a precondition in Scala that evaluates a boolean expression as true or false. It's generally used to validate the execution of the program during runtime. We can see assert is used commonly in testing the functionality of programs.


1 Answers

Testing Either by matching with pattern can be more readable. ScalaTest's Inside trait allows you to make assertions after a pattern match.

import org.scalatest.Inside
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class EitherTest extends AnyFlatSpec with Inside with Matchers {
  val either: Either[Exception, Int] = Right(42)

  either should matchPattern { case Right(42) => }

  inside(either) { case Right(n) =>
    n should be > 1
  }

  val either2: Either[Exception, Int] = Left(new Exception("Bad argument"))

  inside(either2) { case Left(e) =>
    e.getMessage should startWith ("Bad")
  }

}
like image 79
Yuriy Tumakha Avatar answered Sep 23 '22 23:09

Yuriy Tumakha