如何使用C#的FsCheck自定义生成器?

时间:2017-12-14 15:38:46

标签: fscheck

我有以下代码:

var gen = from x in Arb.Generate<int>()
from int y in Gen.Choose(5, 10)
where x > 5
select new tuple { Fst = x, Snd = y };

我可以跑

Prop.ForAll<tuple>(c =>
      Console.WriteLine($"{c.Fst}, {c.Snd}")
).Check(Configuration.Default);

我看到了构建生成器和定义属性的所有方法。

但我发现如何快速找到如何一起使用它们。

1 个答案:

答案 0 :(得分:2)

您需要使用FsCheck注册自定义生成器。请参阅FSCheck docs

简而言之,创建一个类来保留自定义生成器。让公共静态方法返回Arbitrary<T>,其中T是您正在生成的类型。

在您的示例中,您需要将您的生成器包装在Arb.From(...)

的调用中
public class MyGenerators {
    public static Arbitrary<tuple> Tuple() {
        return Arb.From(from x in Arb.Generate<int>()
                        from int y in Gen.Choose(5, 10)
                        where x > 5
                        select new tuple { Fst = x, Snd = y });
    }
}

最后,在运行测试之前调用Arb.Register<MyGenerators>()

相关问题