如何使用FsCheck为可空类型生成null?

时间:2017-03-13 18:56:15

标签: c# fscheck

我有这个似乎有效的生成器,但是当我检查生成的值时,它永远不会选择空值。如何编写将选择空值的生成器。此代码从不为“结束”日期选择空值。

public static Gen<DateTime?> NullableDateTimeGen()
    {
        var list = new List<DateTime?>();

        if (list.Any() == false)
        {
            var endDate = DateTime.Now.AddDays(5);
            var startDate = DateTime.Now.AddDays(-10);

            list.AddRange(Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days)
                .Select(offset => startDate.AddDays(offset))
                .Cast<DateTime?>()
                .ToList());

            list.Add(null);
            list.Insert(0, null);
        }

        return from i in Gen.Choose(0, list.Count - 1)
               select list[i];
    }

    public static Arbitrary<Tuple<DateRange, DateTime>> TestTuple()
    {
        return (from s in NullableDateTimeGen().Where(x => x != null)
                from e in NullableDateTimeGen()
                from p in NullableDateTimeGen().Where(x => x != null)
                where s <= e
                select new Tuple<DateRange, DateTime>(new DateRange(s.Value, e), p.Value))
                .ToArbitrary();
    }

1 个答案:

答案 0 :(得分:0)

问题与FsCheck无关,并且在此声明中:

List/Item

请注意,您从from s in NullableDateTimeGen().Where(x => x != null) from e in NullableDateTimeGen() from p in NullableDateTimeGen().Where(x => x != null) where s <= e select new Tuple<DateRange, DateTime>(new DateRange(s.Value, e), p.Value)) s过滤了空值,因此它们永远不会为空。如果p,唯一可以为null的东西。但是,你做了

e

如果where s <= e 为null,则此比较永远不会为真,因为与null比较的任何内容始终为false。因此,您也会过滤掉e的空值。

修复只需用适合您的方案的任何条件替换该条件,例如

e
相关问题