4

AutoFixture 2に再度アップグレードしようとしていますが、オブジェクトのデータ注釈に問題が発生しています。オブジェクトの例を次に示します。

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 ?!
}

Bonus BitsによるとStringLength、2.4.0の時点でサポートされているはずですが、サポートされていなくても、空の文字列は期待できません。NuGetのv2.7.1を使用しています。データ注釈付きオブジェクトを作成するために必要な、ある種のカスタマイズまたは動作を見逃したことがありますか?

4

1 に答える 1

7

ご報告いただきありがとうございます。

この動作は設計によるものです (その理由は、基本的に、属性自体の説明です)。

[StringLength(255)] をデータ フィールドに適用すると、基本的には 0 文字から 255 文字まで許可されることを意味します。

msdn の説明によると、StringLengthAttribute クラス:

  • データ フィールドで許可される文字の最大長を指定します。[ .NET Framework 3.5 ]

  • データ フィールドで許可される文字の最小長と最大長を指定します。[ .NET フレームワーク 4 ]

現在のバージョン (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)
}
于 2011-12-21T22:21:28.613 に答える