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
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.
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.
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With