简体   繁体   English

scalacheck:生成一个非空字符串

[英]scalacheck: Generate a non empty string

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.您可能需要 someChar 成为非空字符串。 I know you can use whenever in the forAll section but I wonder how to do it in this part of the generator.我知道你可以在forAll部分中的whenever使用,但我想知道如何在生成器的这一部分中使用它。

Thanks谢谢

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))

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希望这有助于某人

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM