まあ、それをテストするのはかなり簡単なはずです。私にとって、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 で動作するいくつかのサンプル単体テストがあるこのサイトも見つかりました。