Translate

miércoles, 14 de septiembre de 2022

Test with Scala check properties

 

I want to test this function : 

def fx(n: Int) : Long = if (n == 0 || n == 1) 1 else fx(n - 1) + fx(n - 2) 


I can write tests in a devilish way, to know if it's ok or I can use Scala check properties.


First I import the scala check :


libraryDependencies += "org.scalameta" %% "munit-scalacheck" % "0.7.29" % Test


It is better if I use the most current version in the version parameter.

Now I can write a test by property :


import munit.ScalaCheckSuite

import org.scalacheck.Prop._


class FxSuite extends ScalaCheckSuite {

  val domain: Gen[Int] = Gen.choose(3, 47) 

  property("Fx(n) is Fx(n -1) + Fx(n -2)") {

    forAll { (n: Int) =>

      fx(n) == fx(n -1) + fx(n -2)

    }

  }

}


And with this we can prove that this property of this function is fulfilled, in the code, we can see the definition of the domain, that is, with this, it will test from 3 to 47.

In conclusion, we can say that a property can be any behavioral characteristic of a method or object that should be fulfilled in any situation. Property-based testing comes from the functional programming community: Haskell's QuickCheck

Link: https://scalameta.org/munit/docs/integrations/scalacheck.html