【问题标题】:AutoFixture: How to set (nested) properties manually based on a patternAutoFixture:如何根据模式手动设置(嵌套)属性
【发布时间】:2018-12-27 10:51:45
【问题描述】:

我有以下嵌套类,它们来自通过 xsd.exe 生成的 XSD 文件。

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>();

我知道我可以使用.with 设置单个属性,但是如何根据特定模式设置属性?尤其是当这些属性嵌套在数组中时?

我基本上必须确保所有以*Specified 结尾的属性都设置为true。包括曾经嵌套到PropertyOne

我是否必须使用我的一种基于反射的方法,例如扩展方法(例如myClassFake.EnableAllProperties())或者是否有实现我的目标的 AutoFixture 方式?


编辑

我知道我可以使用fixture.Register&lt;bool&gt;(() =&gt; true); 将我所有的布尔值设置为真。这解决了我非常具体的问题,但仍然感觉笨拙且不普遍适用。仍在寻找解决此问题的精确方法。

【问题讨论】:

  • 我的那个骗子锤子让我有点困扰;我更愿意投票 将其作为副本关闭。但是,如果其他帖子没有回答您的问题,请告诉我,我将重新打开此问题。
  • 不幸的是,链接的帖子没有回答我的问题。我正在尝试将一组特定的属性(基于模式)设置为特定值。例如。将所有以*Specified 结尾的属性设置为true 或将名称为OID 的所有(嵌套)属性设置为特定的值/生成算法。我希望它以某种方式清楚我想要实现的目标。提前致谢
  • ReflectionVisitor 中使用的 stackoverflow.com/a/47167338/126014 应该也适用于该任务,但我不介意重新提出问题...
  • 谢谢马克。我最终创建了ISpecimenbuilder 的两个实现。虽然我不确定我是否以正确的方式使用RangedNumberRequest

标签: c# tdd system.reflection autofixture


【解决方案1】:

我最终创建了两个ISpecimenBuilder 的实现,它们非常适合我的情况。

这个设置所有以 *Specified 结尾的布尔属性为真,而不影响其他布尔属性。

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));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多