如何让 FsCheck 生成符合 MaxLengthAttribute 的随机字符串?

How to make FsCheck generate random strings that respect MaxLengthAttribute?

FsCheck 是否可以生成符合 MaxLengthAttribute 的随机记录。示例记录类型:

type Person =
    {
        Id: int
        [<System.ComponentModel.DataAnnotations.MaxLength(256)>]
        FirstName: string
        [<System.ComponentModel.DataAnnotations.MaxLength(256)>]
        LastName: string
    }

并非开箱即用,但您可以执行以下操作:

Arb.generate<Person> 
|> Gen.where (fun p -> p.FirstName.Length <= 256 && p.LastName.Length <= 256)

然后是根据传入的东西的类型为Gen.where创建谓词,即使用反射找到具有MaxLength属性的属性,取出值并限制长度.

另请注意,默认情况下,每次测试生成 100 个值的生成字符串的最大长度为 50,因此这可能没有实际意义。