英文:
How do we use the generator with FsCheck?
问题
This link解释了生成器的内容,但没有明确说明如何使用它。
我不确定如何测试生成器生成的列表的内容。
我想要以下代码。
(forall是一个虚构的函数。)
open FsCheck
open FsCheck.Xunit
let isZero x = (x = 0)
let Zeros = Gen.constant 0 |> Gen.sample 0 100
[<Property>]
let TestSample =
forall isZero Zeros
英文:
This link explains the generator, but does not specify exactly how to use it.
I am not sure how to test the contents of the list generated by the generator.
I would like the following code.
(forall is an imaginary function.)
open FsCheck
open FsCheck.Xunit
let isZero x = (x = 0)
let Zeros = Gen.constant 0 |> Gen.sample 0 100
[<Property>]
let TestSample =
forall isZero Zeros
答案1
得分: 1
我同意这可能会令人困惑。最简单的方法是定义一个自定义类型,然后为其创建一个生成器:
open FsCheck
open FsCheck.Xunit
type Zero = MkZero of int
let isZero (MkZero x) = (x = 0)
type Arbs =
// 这是Zero类型的生成器。
static member Zero() =
MkZero 0
|> Gen.constant
|> Arb.fromGen
[<Property>]
let TestSample zeros =
List.forall isZero zeros
[<assembly: Properties(
Arbitrary = [| typeof<Arbs> |])>]
do ()
Zero
类型有一个生成器,用于创建零值。然后,TestSample
属性确认任意零值列表的每个元素确实为零。FsCheck会自动生成各种大小的列表以确认这一点。如果需要,您可以运行时使用 Verbose = true
来查看它们。
由于您想要使用Xunit属性,您必须注册生成器,如这里所述。
正如文档所提到的,在编写属性时不应使用 Gen.sample
。
英文:
I agree that this can be confusing. It's simplest to define a custom type and then create a generator for it:
open FsCheck
open FsCheck.Xunit
type Zero = MkZero of int
let isZero (MkZero x) = (x = 0)
type Arbs =
// This is the generator for the Zero type.
static member Zero() =
MkZero 0
|> Gen.constant
|> Arb.fromGen
[<Property>]
let TestSample zeros =
List.forall isZero zeros
[<assembly: Properties(
Arbitrary = [| typeof<Arbs> |])>]
do ()
The Zero
type has a generator that creates zero values. The TestSample
property then confirms that every element of an arbitrary list of zeros is indeed zero. FsCheck will automatically generate lists of various sizes to confirm this. You can run with Verbose = true
to see them if you want.
Since you want to use Xunit properties, you have to register the generator, as described here.
As the documentation mentions, you shouldn't use Gen.sample
when writing properties.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论