2011-12-21 24 views
3

我正在重新嘗試升級到AutoFixture 2,並且遇到了我的對象上的數據註釋問題。下面是一個例子對象:爲什麼AutoFixture不能使用StringLength數據註釋?

public class Bleh 
{ 
    [StringLength(255)] 
    public string Foo { get; set; } 
    public string Bar { get; set; } 
} 

我試圖創建一個匿名Bleh,但與註釋的財產就要到了空,而不是使用匿名字符串被填充。

[Test] 
public void GetAll_HasContacts() 
{ 
    var fix = new Fixture(); 
    var bleh = fix.CreateAnonymous<Bleh>(); 

    Assert.That(bleh.Bar, Is.Not.Empty); // pass 
    Assert.That(bleh.Foo, Is.Not.Empty); // fail ?! 
} 

根據獎金位,StringLength應該支持爲2.4.0,但就算有人不支持,我不會想到一個空字符串。我從NuGet使用v2.7.1。我是否錯過了創建數據註釋對象所需的某種自定義或行爲?

回答

7

感謝您的舉報!

此行爲是由設計(原因是,基本上,屬性本身的描述)。

通過在數據字段上應用[StringLength(255)],它基本上意味着它可以有0個最多255個字符。

根據MSDN上,所述StringLengthAttribute類的描述:

當前版本(2.7.1)構建於.NET Framework 3.5上。從2.4.0開始支持StringLengthAttribute類。

這就是說,創建的實例有效(只是第二個斷言聲明不是)

這是一個測試通過,使用Validator類從System.ComponentModel.DataAnnotations命名空間驗證創建的實例:

using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using NUnit.Framework; 
using Ploeh.AutoFixture; 

public class Tests 
{ 
    [Test] 
    public void GetAll_HasContacts() 
    { 
     var fixture = new Fixture(); 
     var bleh = fixture.CreateAnonymous<Bleh>(); 

     var context = new ValidationContext(bleh, serviceProvider: null, items: null); 

     // A collection to hold each failed validation. 
     var results = new List<ValidationResult>(); 

     // Returns true if the object validates; otherwise, false. 
     var succeed = Validator.TryValidateObject(bleh, context, 
      results, validateAllProperties: true); 

     Assert.That(succeed, Is.True); // pass 
     Assert.That(results, Is.Empty); // pass 
    } 

    public class Bleh 
    { 
     [StringLength(255)] 
     public string Foo { get; set; } 
     public string Bar { get; set; } 
    } 
} 

更新1

而創建的實例是有效,我相信這可以調整以在範圍內選擇一個隨機數(0 - maximumLength),這樣用戶永遠不會得到空字符串。

我也在論壇here上創建了一個討論。

更新2:如果升級到AutoFixture版本2.7.2(或更新版本)

原來的測試用例現在通過。

[Test] 
public void GetAll_HasContacts() 
{ 
    var fix = new Fixture(); 
    var bleh = fix.CreateAnonymous<Bleh>(); 

    Assert.That(bleh.Bar, Is.Not.Empty); // pass 
    Assert.That(bleh.Foo, Is.Not.Empty); // pass (version 2.7.2 or newer) 
} 
+0

謝謝你的詳細答案。我認爲(有效的)空字符串給我們帶來麻煩的事實表明我們正在濫用AutoFixture,但我仍然感激迅速的更新。我們會盡快嘗試! – ladenedge 2012-01-04 22:29:30

相關問題