2013-07-16 104 views
5

如何修改Float,Double和decimal的AutoFixture創建方法,以便在創建這些類型時還會有餘數?Autofixture - 創建一個float,double或decimal,餘數爲

目前我這樣做,但這會拋出異常。

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

回答

6

試圖通過使用的值,以重新定義類型(double)相同類型(double)確實會產生無限遞歸。但是,通過將種子輸入更改爲另一種類型即可輕鬆完成此工作 - 例如,一個int

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

雙打現在往往也有分數值。

+0

我想我沒有真正想過在後臺如何工作,並且定製創建了無限遞歸。感謝澄清這一點! – Rok

+0

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

Nikos感謝您的幫助,但Mark的回答更符合我所搜索的內容。 – Rok

+1

+1使這個SpecimenBuilder線程安全的任何原因 - 您是否對所有的構建者都這樣做? (我明白爲什麼一個隨機需要被守護,從來沒有想過在SpecimenBuilder中添加這個守護,我永遠不會從Fixture和/或Generator發出來保證線程安全,我當然可以理解,esp給予@ ploeh在V3.0中的不變性工作,它可能相對容易實現)。或者我錯過了一篇博文:P –

+0

+1這也可以在沒有線程安全的情況下工作。幾乎所有的數字序列生成器都是線程安全的,但其中大部分(如果不是全部)都是在3.0之前創建的。 –