By including the OptionValue
trait in our mixin, we get an implicit conversion of Option
. This implicit conversion adds a value method to Option
. The value
method either returns the value from a defined option or alternatively throws TestFailedException
in case the Option
is not defined.
Using this, we are able to test in a single expression both that the Option
is defined and also that it has a certain expected value. Let's look at an example:
val opt:Option[String] = Some("Star Trek")
Our test is as follows:
opt.value.length should be > 5
Alternatively, we can have an assertion here like:
assert(opt.value.length > 5)
If we were using a standard get
method on the option to get the value, we would get a NoSuchElementException
. Therefore by using the OptionValue
trait we are able to reduce the verbosity of our test and eliminate some boilerplate code; for example:
val anotherOpt: Option[String] = None anotherOpt.get .length should be ...