How to make ScalaCheck randomly always generate some special values?

I would like all my properties to always be checked with at least a fixed set of special values โ€‹โ€‹in addition to some random values. I would like to define this in the specification of the generator, and not in every test using this type of generator. For example, if I were creating Ints, I would like my generator to always generate at least 0, 1, and -1 for each test case. Is it possible?

The best I have come up with so far is to make a size generator where the smallest n-sizes correspond to my special cases. This is problematic, at least because all possible sizes are not tested when the maximum number of tests is configured to be lower than the maximum size parameter.

+8
scala scalacheck
source share
1 answer

First of all, Scalacheck already has an offset, so in addition to other Int values, 0, 1, -1, Int.MaxValue and Int.MinValue most likely to be selected. Therefore, if you are worried, do not worry about it. Similarly, blank lines are likely to be generated.

But if you want to reproduce this behavior for something else, use Gen.oneOf or Gen.frequency , possibly in combination with Gen.choose . Since oneOf and frequency take Gen as a parameter, you can combine special cases with generator generators.

For example:

 val myArb: Arbitrary[Int] = Arbitrary(Gen.frequency( 1 -> -1, 1 -> 0, 1 -> 1, 3 -> Arbitrary.arbInt.arbitrary )) 

Pretty much depends on what you requested, with a 50% chance of arbitrary ints (which would be due to the prejudice I spoke of) and 16.6% for each of -1, 0 and 1.

+17
source share

All Articles