Unit testing

Unit tests can be written as in any Scala project. For example, suppose we have a utility method isNumberInRange that takes a string and checks if it's a number in the range [0,3600]. It is defined as follows:

def isNumberInRange(x:String):Boolean = {
    val mayBeNumber = Try{x.toDouble}
    mayBeNumber match{
      case Success(n) => if(n>=0 && n<=3600) true else false
      case Failure(e) => false
    }
  }

Let's write a unit test to check this function using Specs2:

class UtilSpec extends Specification { "range method" should { "fail for Character String" in { Util.isNumberInRange("xyz") should beFalse } "fail for Java null" in { Util.isNumberInRange(null) should beFalse } "fail for Negative numbers" in { Util.isNumberInRange("-2") should beFalse } "pass ...

Get Mastering Play Framework for Scala 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.