如何修改浮点、双精度和小数的 AutoFixture 创建方法,以便在创建这些类型时它们也会有余数?
目前我这样做,但这会引发异常。
var fixture = new Fixture();
fixture.Customize<double>(sb => sb.FromFactory<double>(d => d * 1.33)); //This should add remainder
var value = fixture.Create<double>();
如何修改浮点、双精度和小数的 AutoFixture 创建方法,以便在创建这些类型时它们也会有余数?
目前我这样做,但这会引发异常。
var fixture = new Fixture();
fixture.Customize<double>(sb => sb.FromFactory<double>(d => d * 1.33)); //This should add remainder
var value = fixture.Create<double>();
尝试double
通过使用相同类型 ( double
) 的值来重新定义类型 ( ) 确实会产生无限递归。但是,您可以通过将种子输入更改为另一种类型来轻松完成这项工作 - 例如int
:
var fixture = new Fixture();
fixture.Customize<double>(c => c.FromFactory<int>(i => i * 1.33));
var value = fixture.Create<double>();
双打现在也倾向于具有小数值。
一种选择是使用自定义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);
}
}
}