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 for valid number" in { Util.isNumberInRange("1247") should beTrue } "pass for 0" in { Util.isNumberInRange("0") should beTrue...