Reputation: 17795
What is the best way to generate a non empty string, when in the context of something like this
private def createIndexFn() = {
for{
someChar <- Gen.alphaString
aNumber <- Gen.choose(1,100)
//...
}
yield {
MyThing(AnotherType(someChar.toString), SomeOtherType(aNumber), aNumber)
}
}
where you need maybe someChar to be a non empty string. I know you can use whenever
in the forAll
section but I wonder how to do it in this part of the generator.
Thanks
Upvotes: 12
Views: 4352
Reputation: 4007
Another way is to create a fix length random string
Gen.listOfN(10, Gen.asciiPrintableChar).map(_.mkString)
or to create a random length with a constrained length
for {
n <- Gen.chooseNum(5, 20)
chars <- Gen.listOfN(n, Gen.asciiPrintableChar)
} yield chars.mkString
Upvotes: 1
Reputation: 17795
What I was looking for was:
import org.scalacheck.Arbitrary.arbitrary
arbitrary[String].suchThat(!_.isEmpty)
and can be used like
for {
name <- arbitrary[String].suchThat(!_.isEmpty)
age <- Gen.choose(0, 100)
} yield Person(name, age)
Hopefully this helps someone
Upvotes: 13
Reputation: 533
The accepted answer caused a high ratio of discarded tests for me, I ended up using:
import org.scalacheck._
Arbitrary(Gen.nonEmptyListOf[Char](Arbitrary.arbChar.arbitrary)).map(_.mkString))
Upvotes: 18