我有一个属性,我想在 Stuff
的集合上测试,其中一个 Stuff
满足某个属性。我有一种方法可以生成满足该属性的 Stuff
,也有一种方法可以生成不满足该属性的 Stuff
。
今天,我正在做这样的事情(是的,我在 C# 中使用 FsCheck):
IEnumerable<Stuff> GetStuffCollection(int input)
{
yield return GenerateStuffSatisfyingProperty(input);
yield return GenerateStuffNotSatisfyingProperty(input);
}
[Fact]
public void PropertyForCollectionHolds()
{
Prop.ForAll(Arb.Choose(1,5), input =>
{
var collection = GetStuffCollection(input);
return collection.SatisfiesProperty();
}).VerboseCheckThrowOnFailure();
}
但这对顺序进行了硬编码,即集合中的哪些 Stuff
满足该属性;我也想对此进行仲裁。
一种方法是嵌套 Prop.ForAll
调用;一个生成确定排序的东西的外部一个,以及一个内部的,它是我上面的那个,但将控制排序的参数传递给集合构建器:
IEnumerable<Stuff> GetStuffCollection(int input, bool first)
{
if (first)
{
yield return GenerateStuffSatisfyingProperty(input);
yield return GenerateStuffNotSatisfyingProperty(input);
}
else
{
yield return GenerateStuffNotSatisfyingProperty(input);
yield return GenerateStuffSatisfyingProperty(input);
}
}
[Fact]
public void PropertyForCollectionHolds()
{
Prop.ForAll(Arb.Default.Bool(), first =>
Prop.ForAll(Arb.Choose(1,5), input =>
{
var collection = GetStuffCollection(input, first);
return collection.SatisfiesProperty();
}).VerboseCheckThrowOnFailure()
).VerboseCheckThrowOnFailure();
}
但这感觉笨拙且令人费解。是否有更简单和/或更惯用的方法来实现同样的事情,即测试两个任意值输出的笛卡尔积?
最佳答案
您可以使用Gen.Shuffle
生成不同顺序的序列:
var gen = from input in Gen.Choose(1, 5)
let sc = GetStuffCollection(input)
from shuffled in Gen.Shuffle(sc)
select shuffled
然后
Prop.ForAll(gen, collection => { ... })
关于c# - 在 FsCheck 中将两个生成器组合成一个任意生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44945762/