我有一個自定義的asp.net mvc類驗證屬性。 我的問題是如何單元測試它? 測試該類具有該屬性是一回事,但這實際上並不會測試其中的邏輯。這是我想測試的。如何單元測試我的自定義驗證屬性
[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; }
.....爲了簡潔 }
[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;
}
}
我曾嘗試如下編寫測試,但這不起作用刪除:
[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
保持簡單..嘗試,如果對你有用 - 沒有理由進行更多的測試:) –