问题描述
在F#中,我有一条记录,其中包含一些字段:
In F#, I have a record with a few fields:
type myRecord = { a:float; b:float; c:float }
我正在使用FsCheck来测试使用此记录的某些属性.对于(人为的)示例,
I am using FsCheck to test some properties which use this record.For (a contrived) example,
let verify_this_property (r:myRecord) = myFunction(r) = (r.a * r.b) / r.c
由于 myFunction 的内部实现限制,我希望FsCheck创建测试用例,其中每个字段a,b,c都限于非负浮点数.
Due to the internal implementation restrictions of myFunction, I would like to have FsCheck create test cases in which each of the fields a,b,c are restricted to non-negative floats.
我怀疑这需要为 myRecord 创建一个生成器,但是我找不到任何执行此操作的示例.
I suspect this requires creating a generator for myRecord, but I have not been able to find any examples of how to do this.
任何人都可以提供指导吗?
Can anyone supply guidance?
推荐答案
尝试一下:
type Generators =
static member arbMyRecord =
fun (a,b,c) -> { myRecord.a = a; b = b; c = c }
<!> (Arb.generate<float> |> Gen.suchThat ((<) 0.) |> Gen.three)
|> Arb.fromGen
Arb.register<Generators>() |> ignore
Check.Quick verify_this_property
<!>
是一个后缀map
,对于应用样式很有用.这是一个等效的生成器:
The <!>
is an infix map
, useful for applicative style. This is an equivalent generator:
type Generators =
static member arbMyRecord =
Arb.generate<float>
|> Gen.suchThat ((<) 0.)
|> Gen.three
|> Gen.map (fun (a,b,c) -> { myRecord.a = a; b = b; c = c })
|> Arb.fromGen
如果您不想全局注册生成器,则可以使用forAll
:
If you don't want to globally register your generator, you can use forAll
:
Check.Quick (forAll Generators.arbMyRecord verify_this_property)
向左收缩是一种锻炼;)
Shrinking left as an exercise ;)
这篇关于在FsCheck中,如何生成带有非负字段的测试记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!