O'Reilly logo

Scala Test-Driven Development by Gaurav Sood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required