AutoFixture:如何正确使用BooleanSwitch()从ISpecimenBuilder实现生成随机值?

问题描述 投票:-1回答:1

我有一个完全由字符串类型的一类......我不满意这点,但不能改变它。这个类是一些CSV格式越来越解析的代表性。

现在,我想生成假的实例。例如,我想生成随机布尔值,并将其转换为字符串。我已经为此创建ISpecimenBuilder的实施迄今的工作。

public class MyPropertyBuilder : ISpecimenBuilder
{
    private readonly Random rand;

    public MyPropertyBuilder()
    {
        this.rand = new Random();
    }
    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as PropertyInfo;

        if (pi == null)
        {
            return new NoSpecimen();
        }

        if (pi.PropertyType == typeof(string) && pi.Name == "MyPropertyName")
        {
            return (this.rand.NextDouble() > 0.5).ToString();
        }

        return new NoSpecimen();
    }
}

但我有点不上如何正确使用像context.Resolve() *RequestRangedNumberRequest()类如下面的代码片段理解。

public class UnsignedIntegerNumberBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as PropertyInfo;

        if (pi == null)
        {
            return new NoSpecimen();
        }

        if (pi.PropertyType == typeof(string) && pi.Name == "ORDER_NR")
        {
            return context.Resolve(new RangedNumberRequest(typeof(int), 0, int.MaxValue)).ToString();
        }

        return new NoSpecimen();
    }
}

当然,我可以实现我自己的方式来生成随机布尔值,使MyPropertyBuilder返回,但犯规是打败AutoFixture的目的,我莫名其妙地重新发明了一些primitve类型的数据生成的一部分?

所以我想的问题是:如何才能正确使用AutoFixtures布尔值生成一个特定的属性?

c# tdd autofixture
1个回答
0
投票

如果我理解正确的类的所有属性的类型string的,但表示其他数据类型(布尔,整数或日期)。

我的建议是建立与您预计将物业类型一FixtureBuilder类。随着Autfixture您将能够生成随机值,然后将其转换为CSV表示。

public class CsvData
{
    public string Enabled { get; set; }
    public string Quantity { get; set; }
    public string Price { get; set; }
}

public class CsvDataBuilder
{
    public bool Enabled { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; } 

    public CsvData ToCsvData()
    {
        return new CsvData
        {
            Enabled = Enabled.ToString(),
            Quantity = Quantity.ToString(),
            Price = Price.ToString()
        };
    }
}

然后,在测试中,你可以中创建建设者

var dataFromCsv = new Fixture().Create<CsvDataBuilder>().ToCsvData();
© www.soinside.com 2019 - 2024. All rights reserved.