当我在进行单元测试我的自定义验证逻辑时,我收到此错误
发生了'System.ArgumentNullException'类型的异常 System.ComponentModel.DataAnnotations.dll但未在用户中处理 代码
附加信息:值不能为空。
这是我的完整代码。所以,请看到并告诉我我在哪里犯了错误?
public class DateValTest
{
[Display(Name = "Start Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
[Display(Name = "End Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[MyDate(ErrorMessage = "Back date entry not allowed")]
[DateGreaterThanAttribute(otherPropertyName = "StartDate", ErrorMessage = "End date must be greater than start date")]
public DateTime? EndDate { get; set; }
}
public class MyDateAttribute : ValidationAttribute, IClientValidatable
{
public DateTime _MinDate;
public MyDateAttribute()
{
_MinDate = DateTime.Today;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime _EndDat = DateTime.Parse(value.ToString(), CultureInfo.InvariantCulture);
DateTime _CurDate = DateTime.Today;
int cmp = _EndDat.CompareTo(_CurDate);
if (cmp > 0)
{
// date1 is greater means date1 is comes after date2
return ValidationResult.Success;
}
else if (cmp < 0)
{
// date2 is greater means date1 is comes after date1
return new ValidationResult(ErrorMessage);
}
else
{
// date1 is same as date2
return ValidationResult.Success;
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "restrictbackdates",
};
rule.ValidationParameters.Add("mindate", _MinDate);
yield return rule;
}
}
[TestClass]
public class MyDateAttribute_Test
{
[TestMethod]
[ExpectedException(typeof(ValidationException))]
public void Test_EndDateIsInvalidIFBackDate()
{
var validationResults = new List<ValidationResult>();
DateValTest model = new DateValTest() { EndDate = DateTime.Today.AddDays(10) };
ValidationContext context = new ValidationContext(model);
Validator.TryValidateProperty(model, context, validationResults);
Assert.IsTrue(validationResults.Count > 0);
}
}
突出显示我犯错误的区域。感谢
答案 0 :(得分:0)
我这样解决。
[TestMethod]
//[ExpectedException(typeof(ValidationException))]
public void Test_EndDateIsInvalidIFBackDate()
{
var validationResults = new List<ValidationResult>();
DateValTest model = new DateValTest() { StartDate = DateTime.Today, EndDate = DateTime.Today.AddDays(10) };
ValidationContext context = new ValidationContext(model);
MyDateAttribute attribute = new MyDateAttribute();
//attribute.Validate(model.EndDate, context);
Validator.TryValidateObject(model, context, validationResults, true);
//Assert.IsFalse(validationResults.Count > 0);
Assert.AreEqual(false, (validationResults.Count > 0), "Test Equalateral");
//Assert.IsTrue(validationResults.Any(vr => vr.ErrorMessage == "Back date entry not allowed"));
}