Autofixture - 使用余数创建一个float,double或decimal

时间:2013-07-16 09:31:01

标签: c# tdd autofixture

如何为float,double和decimal修改AutoFixture create方法,以便在创建这些类型时它们还有余数?

目前我这样做,但这引发了异常。

var fixture = new Fixture();
fixture.Customize<double>(sb => sb.FromFactory<double>(d => d * 1.33));   //This should add remainder
var value = fixture.Create<double>();

2 个答案:

答案 0 :(得分:9)

尝试使用相同类型的值(double)重新定义类型(double),实际上会产生无限递归。但是,您可以通过将种子输入更改为另一种类型来轻松完成此工作 - 例如int

var fixture = new Fixture();
fixture.Customize<double>(c => c.FromFactory<int>(i => i * 1.33));
var value = fixture.Create<double>();

双打现在也会有小数值。

答案 1 :(得分:5)

一种选择是使用自定义ISpecimenBuilder

var fixture = new Fixture();
fixture.Customizations.Add(
    new RandomDoublePrecisionFloatingPointSequenceGenerator());

RandomDoublePrecisionFloatingPointSequenceGenerator可能如下所示:

internal class RandomDoublePrecisionFloatingPointSequenceGenerator
    : ISpecimenBuilder
{
    private readonly object syncRoot;
    private readonly Random random;

    internal RandomDoublePrecisionFloatingPointSequenceGenerator()
    {
        this.syncRoot = new object();
        this.random = new Random();
    }

    public object Create(object request, ISpecimenContext context)
    {
        var type = request as Type;
        if (type == null)
            return new NoSpecimen(request);

        return this.CreateRandom(type);
    }

    private double GetNextRandom()
    {
        lock (this.syncRoot)
        {
            return this.random.NextDouble();
        }
    }

    private object CreateRandom(Type request)
    {
        switch (Type.GetTypeCode(request))
        {
            case TypeCode.Decimal:
                return (decimal)
                    this.GetNextRandom();

            case TypeCode.Double:
                return (double)
                    this.GetNextRandom();

            case TypeCode.Single:
                return (float)
                    this.GetNextRandom();

            default:
                return new NoSpecimen(request);
        }
    }
}