私はカスタムasp.net mvcクラス検証属性を持っています。 私の質問は、どのようにユニットテストできるのですか? クラスに属性があることをテストするのは一つのことですが、実際にその内部のロジックをテストすることはありません。これは私がテストしたいものです。私は次のようにテストを書くことを試みたが、これは動作しませんユニットのカスタム検証属性をユニットテストするには
[AttributeUsage(AttributeTargets.Class)]
public class EligabilityStudentDebtsAttribute : ValidationAttribute
{
// If AnyDebts is true then
// StudentDebts must be true or false
public override bool IsValid(object value)
{
Eligability elig = (Eligability)value;
bool ok = true;
if (elig.AnyDebts == true)
{
if (elig.StudentDebts == null)
{
ok = false;
}
}
return ok;
}
}
簡潔 }のために取り外さ
[Serializable]
[EligabilityStudentDebtsAttribute(ErrorMessage = "You must answer yes or no to all questions")]
public class Eligability
{
[BooleanRequiredToBeTrue(ErrorMessage = "You must agree to the statements listed")]
public bool StatementAgree { get; set; }
[Required(ErrorMessage = "Please choose an option")]
public bool? Income { get; set; }
.....:
[TestMethod]
public void Eligability_model_StudentDebts_is_required_if_AnyDebts_is_true()
{
// Arrange
var eligability = new Eligability();
var controller = new ApplicationController();
// Act
controller.ModelState.Clear();
controller.ValidateModel(eligability);
var actionResult = controller.Section2(eligability,null,string.Empty);
// Assert
Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
Assert.AreEqual(string.Empty, ((ViewResult)actionResult).ViewName);
Assert.AreEqual(eligability, ((ViewResult)actionResult).ViewData.Model);
Assert.IsFalse(((ViewResult)actionResult).ViewData.ModelState.IsValid);
}
ModelStateDictionary
はしていませんこのカスタム属性のキーが含まれています。 標準検証属性の属性のみが含まれています。
これはなぜですか?
これらのカスタム属性をテストする最良の方法は何ですか?
Doh!もちろん! – MightyAtom
これはクロスプロパティ検証を実行する最善の方法ですか? (複数のプロパティを含むモデル検証) – MightyAtom
単純なままにしてください。もしあなたがうまくいくなら、より多くのcompexテストを行う理由はありません:) –