まあ、それはかなり簡単なはずのテスト。私にとっては、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の検証ランナーとそれを呼び出す方法を前提としています。
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);
}
}
:私はそうのようにランナーを呼ぶの上に小さなサンプルで
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);
}
}
:あなたがここにいない場合は、私は(私はスティーブサンダーソンさんのブログからニック入り)テストに使用本当に単純なものです
これはすべて過度に単純化されていますが、機能します。 MVCを使用するときのよりよい解決策は、codeplexから得ることができるMvc.DataAnnotionsモデルバインダーです。 DefaultModelBinderから独自のモデルバインダーを作成するのは簡単ですが、すでに完了して以来気にする必要はありません。
これが役に立ちます。
PS。また、DataAnnotationsで動作するいくつかのサンプル単体テストがあるthis siteが見つかりました。