ScalaCheck

ScalaCheck (http://www.scalacheck.org) is a framework for automated PBT in Scala. It works great with SBT or IntelliJ IDEA and also has a built-in test runner and can be used standalone because of this. It also integrates well with ScalaTest and specs2

ScalaCheck is an external dependency, so we need to add it to the build.sbt:

libraryDependencies += "org.scalacheck" %% "scalacheck" % "1.14.0" % Test

In order to be able to play with the code in REPL, we'll need to add it to the default scope (by removing the % Test part (this is already done in the chapter's code) and start the REPL with SBT dependencies. If you don't know how to do this, please refer to the Appendix A, Preparing the Environment and Running Code Samples, where we explain it in detail.

Now, we can define and verify our first property:

scala> import org.scalacheck.Prop.forAll
import org.scalacheck.Prop.forAll

scala> val stringLengthProp = forAll { (_: String).length >= 0 }
stringLength: org.scalacheck.Prop = Prop

scala> stringLengthProp.check
+ OK, passed 100 tests.

We just defined and verified that all Strings have non-negative lengths! Confused a bit? Let's take a closer look how it was done.

In the first line, we imported a forAll property factory. In essence, its purpose is to convert functions into properties.

In our case, in the second line the function is of a type String => Boolean. Naturally, there is some implicit magic in play. Among other things, there is an implicit conversion Boolean => Property and an Arbitrary[String] which provides a test data, in our case, random strings.

In the third line we call a check method available on the Prop (ScalaCheck uses this name as an abbreviation for "property") among other combination and execution methods to execute our test using the default configuration. Hence, it runs with 100 random strings as an input data.

Now that we've got a feeling for how the PBT looks in general, we'll rigorously approach each aspect of it, starting with properties.

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

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