Further, in our series on Acceptance Test Driven Development, we would look at generating random test values with the ScalaCheck framework. In our last post we looked at, how we make our test logic respect the DRY principle by defining the values in a table. However, in many situations, you would like to generate the values dynamically so that we do not have to fill a lot of values in the table. Let us see how this is done with the help of a library called ScalaCheck
We would change our test case a bit for dynamic value generation. Look at the code sample below
The important thing to note here is the trait called GeneratorDrivenPropertyChecks. This trait facilitates property checks against generated data using ScalaCheck.
In order to include ScalaCheck library in your project, we would need to include the following dependency
Let us look at the complete code sample
As you would notice, most of the things are quite the same as in our last example where we were using TableDrivenPropertyChecks. The difference being that now, instead of using Table driven values, we end up Generating values.
This code generates numbers between the given range. So it is -10 to 300 for validNumberOnes and between 10 to 15 for validNumberTwos.
Trait GeneratorDrivenPropertyChecks contains forAll method that provides various ways to check properties using generated data. Here, we are not only getting values of valiNumberOnes and validNumberTwos but also specifying the configuration parameters like minSuccessful, maxDiscarded and workers
Notice that the software under test in this case is the ActualBusinessImplementation class.
When we execute it, the system runs 500 successful tests with various value combinations and hence we know that the result is correct. The output of the evaluation would look something like this.
The ordering of the output looks a little weird because we are running the evaluation with four threads. As always the code is present on the Knoldus Github account.
Hence, as we saw it is easy to generate values with ScalaCheck and pass it to our test case. We can also specify the minimum number of generated value test which would need to be performed before we say that our code is good. In a follow up post to this ATDD series, we would look at another interesting candidate which would make life easy for stakeholders and developers. Till then.