12

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

Valy Dia
  • 2,781
  • 2
  • 12
  • 32
roundcrisis
  • 17,276
  • 14
  • 60
  • 92

3 Answers3

17

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))
Matthew Pickering
  • 523
  • 1
  • 5
  • 16
13

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

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
roundcrisis
  • 17,276
  • 14
  • 60
  • 92
1

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
Channing Walton
  • 3,977
  • 1
  • 30
  • 59