C# AutoFixture:如何基于图案手动设置(嵌套)特性
我有以下嵌套类,它们来自通过XSD.exe生成的XSD文件C# AutoFixture:如何基于图案手动设置(嵌套)特性,c#,tdd,system.reflection,autofixture,C#,Tdd,System.reflection,Autofixture,我有以下嵌套类,它们来自通过XSD.exe生成的XSD文件 public class MyClass { public AnotherClass[] PropertyOne; public DateTime PropertyTwo; public bool PropertyTwoSpecified } public class AnotherClass { public DateTime AnotherPropertyOne public bo
public class MyClass
{
public AnotherClass[] PropertyOne;
public DateTime PropertyTwo;
public bool PropertyTwoSpecified
}
public class AnotherClass
{
public DateTime AnotherPropertyOne
public bool AnotherPropertyOneSpecified
public int AnotherPropertyTwo
public bool AnotherPropertyTwoSpecified
}
现在我想使用AutoFixture生成带有合成数据的实例
var fixture = new Fixture();
fixture.Customize(new AutoFakeItEasyCustomization());
var myClassFake = fixture.Create<MyClass>();
var fixture=newfixture();
fixture.Customize(新的AutoFakeItEasyCustomization());
var myClassFake=fixture.Create();
我知道我可以使用.with
设置单个属性,但是如何根据特定模式设置属性?尤其是当这些属性嵌套在数组中时
我基本上必须确保所有以指定的*结尾的属性都设置为true
。包括曾经嵌套在属性中的
我是否必须使用基于一个反射的方法,例如扩展方法(例如myClassFake.EnableAllProperties()
),或者是否有一种自动夹具方法来实现我的目标
编辑
我知道我可以使用fixture.Register(()=>true)
将所有布尔设置为true。这解决了我非常具体的问题,但仍然感觉笨拙,不适用于一般情况。仍然在寻找解决这个问题的精确方法。我最终创建了两个ISpecimenBuilder
的实现,它们非常适合我的情况
此选项将所有以*结尾的布尔属性设置为true,而不影响其他布尔属性
public class SpecifiedBoolSpecimenBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var pi = request as PropertyInfo;
if (pi == null)
{
return new NoSpecimen();
}
if (pi.PropertyType != typeof(bool) || !pi.Name.EndsWith("Specified"))
{
return new NoSpecimen();
}
return true;
}
}
此选项将特定属性设置为一个随机值范围:
public class OidSpecimenBuilder : ISpecimenBuilder
{
public int Min { get; set; }
public int Max { get; set; }
public OidSpecimenBuilder(int min, int max)
{
this.Min = min;
this.Max = max;
}
public object Create(object request, ISpecimenContext context)
{
var pi = request as PropertyInfo;
if (pi == null)
{
return new NoSpecimen();
}
if (pi.PropertyType != typeof(long) || pi.Name != "OID")
{
return new NoSpecimen();
}
return context.Resolve(new RangedNumberRequest(typeof(long), Min, Max));
}
}
我那把被骗的锤子让我有点烦;我更愿意投票将此作为副本关闭。如果其他帖子没有回答你的问题,请让我知道,我会重新打开这个问题。不幸的是,链接帖子没有回答我的问题。我试图将一组特定的属性(基于模式)设置为特定的值。例如,将所有以指定的*结尾的属性设置为true
,或将名称为OID
的所有(嵌套)属性设置为特定值/生成算法。我希望我所要达到的目标是明确的。提前感谢中使用的ReflectionVisitor
对于该任务也应该有用,但我不介意重新打开问题…Thx标记。我最终创建了两个ISpecimenbuilder
的实现。虽然我不确定我是否正确使用了RangedNumber请求
。如果你给出答案,你更有可能得到关于解决方案的反馈。这将是使用堆栈溢出的完美方式:)