3

I am using the ScalaCheck generator alphaStr to generate Strings but they always come back empty. For eg. the following test fails on the first string.

class GenSpec extends FunSuite with GeneratorDrivenPropertyChecks with Matchers {
  implicit val noShrink: Shrink[List[Char]] = Shrink.shrinkAny
  test("alphaStr") {
    forAll(Gen.alphaStr) { case str =>
      println(str)
      str.isEmpty shouldBe false
    }
  }
}

Output:

TestFailedException was thrown during property evaluation.
  Message: true was not equal to false
  Location: (GenSpec.scala:12)
  Occurred when passed generated values (
    arg0 = ""
  )
ScalaTestFailureLocation: org.scalatest.prop.GeneratorDrivenPropertyChecks$class at (GeneratorDrivenPropertyChecks.scala:914)
org.scalatest.exceptions.GeneratorDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation.
  Message: true was not equal to false
  Location: (GenSpec.scala:12)
  Occurred when passed generated values (
    arg0 = ""
  )

I have added noShrink to ensure that the underlying list of chars does not get shrunk. But it still fails. Does anyone know why?

Saket
  • 3,079
  • 3
  • 29
  • 48

2 Answers2

3

Not sure that shrink will work in this case and alphaStr doesn't concern itself with empty values but as alternative you can use filter and the string length:

Gen.alphaStr.filter(_.trim.length > 0)
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
  • 3
    An alternative is `Gen.alphaStr.suchThat(_.nonEmpty)` but I was wondering why does it generate an empty string a the first value. – Saket Aug 25 '16 at 15:26
1

Gen.alphaStr.suchThat(_.nonEmpty) perfectly works, but sometimes its sample might generate None (indeed when the original alphaStr generator was the empty string). This is sometimes not desirable.

An alternative is concatenating the results of Gen.alphaChar and Gen.alphaStr, like this:

Gen.zip(Gen.alphaChar, Gen.alphaStr).map(t => t._1 + t._2)
juanmirocks
  • 4,786
  • 5
  • 46
  • 46