[英]Can Autofixture enumerate all objects given a list of possible values for each property
我正处于TDD的中间,可以根据属性过滤对象。 过滤规则很多,每个都经常考虑多个属性。
我开始检查每个规则,通过提供它们被过滤的所有对象属性的枚举,但这很快就变得无趣了,我想解决在我的大脑被“复制 - 粘贴degenerescence”吃掉之前的痛苦。
AutoFixture在这种情况下应该非常有用,但我无法在FAQ或CheatSheet中找到这些信息。 Ploeh的博客填充列表看起来很有前景,但对我来说不够深入。
所以,给出以下课程
public class Possibility
{
public int? aValue {get;set;}
public int? anotherValue {get;set;}
}
我可以得到一个Possibility
列表,其中每个类包含一个可能的预定义值aValue
和anotherValue
枚举? 例如,给定的值[null, 10, 20]
对于aValue
和[null, 42]
为anotherValue
,我将被返回的实例6 Possibility
。
如果不是,我怎么能在每个对象类型自己编码之外得到这种行为?
鉴于问题的价值:
null
, 10
, 20
为aValue
null
, 42
, --
对于anotherValue
以下是使用Generator<T>
进行AutoFixture的一种方法:
[Fact]
public void CustomizedAutoFixtureTest()
{
var fixture = new Fixture();
fixture.Customizations.Add(
new PossibilityCustomization());
var possibilities =
new Generator<Possibility>(fixture).Take(3);
// 1st iteration
// -------------------
// aValue | null
// anotherValue | null
// 2nd iteration
// -------------------
// aValue | 10
// anotherValue | 42
// 3rd iteration
// -------------------
// aValue | 20
// anotherValue | (Queue is empty, generated by AutoFixture.)
}
在内部, PossibilityCustomization
使用Queue类提供预定义值 - 当它用完预定义值时,它使用AutoFixture。
private class PossibilityCustomization : ISpecimenBuilder
{
private readonly Queue<int?> aValues =
new Queue<int?>(new int?[] { null, 10, 20 });
private readonly Queue<int?> anotherValues =
new Queue<int?>(new int?[] { null, 42 });
public object Create(object request, ISpecimenContext context)
{
var pi = request as PropertyInfo;
if (pi != null)
{
if (pi.Name == "aValue" && aValues.Any())
return aValues.Dequeue();
if (pi.Name == "anotherValue" && anotherValues.Any())
return anotherValues.Dequeue();
}
return new NoSpecimen();
}
}
AutoFixture会生成匿名值 ,因此当您已经拥有要组合的精确值时,它可能不是完全适合该作业的正确工具。
如果你在NUnit上,你可以这样做:
[Test]
public void HowToGetPermutations(
[Values(null, 10, 20)] int? aValue,
[Values(null, 42)] int? anotherValue)
{
// Test and assert
}
这将运行此测试方法六次 - 每次可能的排列一次。
这是我希望xUnit.net拥有的为数不多的功能之一,但它没有......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.