首页 > 解决方案 > 如何限制 FsCheck 中的输入值?

问题描述

我有一个像这样的 FsCheck-Property:

[Property]
public Property ConversionCanBeInversedForAllUnits(double input, string unit1, string unit2) 
{ ... }

FsCheck 将提供随机值。我想将字符串的输入限制为某些固定集合的成员。

显而易见的解决方案有效:

[Property]
public Property ConversionCanBeInversedForAllUnits(double input, int unit1Int, int unit2Int) 
{
 string unit1 = units[unit1Int % units.Lenght];
 string unit2 = units[unit2Int % units.Lenght];
 input = math.clamp(min, input, max);
}

我不认为它缩进以这种方式使用。

第二次尝试没有成功。首先我添加了一些类

  public class MyTestDataCreator
  {
    private static string[] lengthUnits = new string[] { "m", "mm" };
    public static Arbitrary<string> lenghtunits()
    {
      // Does not compile.
      return FsCheck.Gen.Choose(0, lengthUnits.Length).Select(index => lengthUnits[index]);
    }

    public Gen<double> DoubleGen()
    {
      return FsCheck.Gen.Choose(0, 1000);
    }
}

并将属性更改为

[Property(Arbitrary = new Type[] { typeof(MyTestDataCreator) })]

这让我例外

Message: System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
---- System.Exception : No instances found on type Prop.MyTestDataCreator. Check that the type is public and has public static members with the right signature.

这就引出了一个问题:正确的签名是什么?

标签: c#fscheck

解决方案


lengthunits()具有正确的签名:返回一个Arbitrary实例和一个没有参数的方法。

尝试通过调用它来将 aGen<T>变成a 。Arbitrary<T>ToArbitrary()

Arbitrary如果您想编写收缩器,它将变得有用。任意 = 生成器 + 收缩器。


推荐阅读