1

xValのテストを生成する方法、またはDataAnnotations属性のポイントを知っている人はいますか

ここに、テストしたい同じコードがあります

[MetadataType(typeof(CategoryValidation))] public 部分クラス Category : CustomValidation { }

public class CategoryValidation
{
    [Required]
    public string CategoryId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [StringLength(4)]
    public string CostCode { get; set; }

}
4

1 に答える 1

2

まあ、それをテストするのはかなり簡単なはずです。私にとって、NUnitを使用すると、次のようになります。

    [Test]
    [ExpectedException(typeof(RulesException))]
    public void Cannot_Save_Large_Data_In_Color()
    {

        var scheme = ColorScheme.Create();
        scheme.Color1 = "1234567890ABCDEF";
        scheme.Validate();
        Assert.Fail("Should have thrown a DataValidationException.");
    }

これは、DataAnnotations の検証ランナーが既に構築されており、それを呼び出す方法があることを前提としています。ここにない場合は、私がテストに使用する非常に単純化されたものです (Steve Sanderson のブログからニックネームを付けました)。

internal static class DataAnnotationsValidationRunner
{
    public static IEnumerable<ErrorInfo> GetErrors(object instance)
    {
        return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
               from attribute in prop.Attributes.OfType<ValidationAttribute>()
               where !attribute.IsValid(prop.GetValue(instance))
               select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
    }
}

上記の小さなサンプルでは、​​次のようにランナーを呼び出します。

public class ColorScheme
{
     [Required]
     [StringLength(6)]
     public string Color1 {get; set; }

     public void Validate()
     {
         var errors = DataAnnotationsValidationRunner.GetErrors(this);
         if(errors.Any())
             throw new RulesException(errors);
     }
}

これはすべて過度に単純化されていますが、機能します。MVC を使用する場合のより良い解決策は、 codeplex から取得できる Mvc.DataAnnotions モデル バインダーです。DefaultModelBinder から独自のモデル バインダーを作成するのは簡単ですが、既に作成されているので気にする必要はありません。

お役に立てれば。

PS。また、DataAnnotations で動作するいくつかのサンプル単体テストがあるこのサイトも見つかりました。

于 2009-07-13T14:20:35.383 に答える