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
    }

    "pass for 3600" in {
      Util.isNumberInRange("3600") should beTrue
    }
    
  }
}

These scenarios can also be written using ScalaTest with slight modifications:

class UtilTest extends FlatSpec with Matchers {

  "Character String" should "not be in range" in {
    Util.isNumberInRange("xyz") should be(false)
  }

  "Java null" should "not be in range" in {
    Util.isNumberInRange(null) should be(false)
  }

  "Negative numbers" should "not be in range" in {
    Util.isNumberInRange("-2") should be(false)
  }

  "valid number" should "be in range" in {
    Util.isNumberInRange("1247") should be(true)
  }

  "0" should "be in range" in {
    Util.isNumberInRange("0") should be(true)
  }

  "3600" should "be in range" in {
    Util.isNumberInRange("3600") should be(true)
  }
}

Unit tests that need to rely on external dependencies and data service layers should be defined using mocks. Mocking is the process of simulating actual behavior. Mockito, ScalaMock, EasyMock, and jMock are some of the libraries that facilitate mocking.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.62.122