How to write a test with 2 parameters when the generation of the second depends on the 1st?

StackOverflow https://stackoverflow.com/questions/21238490

  •  30-09-2022
  •  | 
  •  

Question

How can I write a generator for the second argument someBoundedInt which will generate an Int randomly between the values generated for minmaxBound?

val boundedIntProperty = forAll {
  (minmaxBound: (Int,Int), someBoundedInt: Int) => 
    minmaxBound._1 <= someBoundedInt && someBoundedInt <= minmaxBound._2

}
Était-ce utile?

La solution

You can nest calls to forAll like this:

val boundedIntProperty = forAll { (minBound: Int, maxBound: Int) =>
  forAll( Gen.choose(minBound, maxBound) ) { someBoundedInt =>
    ...
  }
}

Note that above, minBound can be larger than maxBound sometimes, which will make Gen.choose fail (not produce a value). So you probably want to generate your bounds in a smarter way too.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top