我有一个自定义的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; }
.....removed for brevity }
[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
不包含此自定义属性的键。它仅包含标准验证属性的属性。
为什么会这样呢?
测试这些自定义属性的最佳方法是什么?
System.ComponentModel.DataAnnotations
的引用,否则您将看不到IsValid
方法(它也无法编译,但我花了一段时间才发现这个问题)。 - Liam