Question

I use ScalaTest and Scalacheck together. Here is my lazy pairs (It doesn't work because here we get Gen[(Int, Int)] as a result instead of Tuples2 so I can't use pattern matching):

private lazy val (startInterval, endInterval) =
  for {
    start <- Gen.choose(-10000, 10000)
    end <- Gen.choose(-10000, 10000) if end > start
  } yield (start, end)

In order to use the two parameters for forAll I would like to use the two mentioned vals above in this way:

forAll (endInterval, startInterval) { (start: Int, end: Int) =>
        assert(sumOfCubes(start, end) === 0)
      }

I can create one Gen[(Int, Int)] in this way:

private lazy val genPairs =
  for {
    start <- Gen.choose(-10000, 10000)
    end <- Gen.choose(-10000, 10000) if end > start
  } yield (start, end)

But after that I cannot access to the elements by names.

It might be an easy question who uses scalacheck for a long time but I'm just a begineer and tried many solutions so Any idea how can I solve this problem?

EDIT: One solution could be the use of whenever:

private lazy val startInterval = Gen.choose(-10000, 10000)
private lazy val endInterval = Gen.choose(-10000, 10000)

And:

forAll (startInterval, endInterval) { (start: Int, end: Int) =>
        whenever(start > end) {
          assert(sumOfCubes(start, end) === 0)
        }
}

However there will be the possibility of test fail when all of the generated start and end don't fulfill the condition. So it's hardly the best solution (or a good one at least).

Was it helpful?

Solution

You access them with scalatest's forAll function like this:

  import org.scalatest.prop.GeneratorDrivenPropertyChecks._

  forAll (genPairs) { 
    case (start, end) => doSomething(start, end)
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top