1
votes

I need generate list of objects. Each objects must contain predestined value and generated value. I created the generator but not sure that this is the true way. Is there any ways to make it more readable?

 object Test {
      case class A(myInt: Int, randomInt: Int)
      val list = List(1, 2, 3, 4, 5)
      val subListGen = Gen.someOf(list)
      val randomIntGen = Gen.choose(0,10)
      import scala.collection.JavaConverters._
      val seqAGen: Gen[Seq[A]] = for {
        subsetMyInts <- subListGen
        seqOfRandomIntsWithSizeEqualGenSubList <- Gen.sequence(subsetMyInts.map(x => randomIntGen))
      } yield {
        subsetMyInts.zip(seqOfRandomIntsWithSizeEqualGenSubList.asScala.toList).map(x => A(x._1, x._2))
      }
    }
2
As Arseniy noticed: if you have a type of A, it's idiomatic to have a generator tailored for that type.ppopoff

2 Answers

2
votes

First, we might want to implement a generator for a single instance:

val aGen: Gen[A] = for {
  myInt <- Gen.oneOf(list:_*)
  randomInt <- Gen.choose(0, 10)
} yield A(myInt, randomInt)

And then - generate a list of these objects:

val listOfAGen = Gen.listOf(aGen)

This will work if you don't care about the uniqueness of myInts.

0
votes

The approach with using .sample

object Test {
  case class A(myInt: Int, randomInt: Int)
  val list = List(1, 2, 3, 4, 5)
  val randomIntGen = Gen.choose(0,10)
  val seqAGen: Gen[Seq[A]] =  Gen.someOf(list.flatMap(myInt => randomIntGen.sample.map(A(myInt, _))))
}