ご報告いただきありがとうございます。
この動作は設計によるものです (その理由は、基本的に、属性自体の説明です)。
[StringLength(255)] をデータ フィールドに適用すると、基本的には 0 文字から 255 文字まで許可されることを意味します。
msdn の説明によると、StringLengthAttribute クラス:
現在のバージョン (2.7.1) は、.NET Framework 3.5 上に構築されています。StringLengthAttribute クラスは 2.4.0 以降でサポートされています。
そうは言っても、作成されたインスタンスは有効です(2 番目のアサーション ステートメントが有効でないだけです)。
System.ComponentModel.DataAnnotations 名前空間のValidatorクラスを使用して、作成されたインスタンスを検証する合格テストを次に示します。
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) 内の乱数を選択するように調整できると思います。
こちらのフォーラムでもディスカッションを作成しました。
更新 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)
}