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

Rok*_*Rok 7 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>();
Run Code Online (Sandbox Code Playgroud)

Mar*_*ann 10

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

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

双打现在也倾向于具有小数值.


Nik*_*nis 5

一种选择是使用自定义ISpecimenBuilder:

var fixture = new Fixture();
fixture.Customizations.Add(
    new RandomDoublePrecisionFloatingPointSequenceGenerator());
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)