The OptionValue trait

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 ...

Get Scala Test-Driven Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.