I am bit familiar with ASP.Net MVC but weak in writing unit tests. I read an article about how to write unit test code when working with these classes and interface ValidationAttribute
and IClientValidatable
. Here is the link to the article:
http://www.codeproject.com/Articles/990538/Unit-Testing-Data-Validation-with-MVC
I was doing custom validation. The custom validation code as follows
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;
}
}
So, I tried to write unit test code for the above validation. Please look at my unit test code and tell me if I am going in the right direction because I do not know if I wrote it properly or miss something. please have a look.
[TestClass]
public class MyDateAttribute_Test
{
[TestMethod]
public void IsValid_Test()
{
var model = new MyDateAttribute { _MinDate = DateTime.Today.AddDays(-10) }; //set value
ExecuteValidation(model, "Back date entry not allowed");
}
private void ExecuteValidation(object model, string exceptionMessage)
{
try
{
var contex = new ValidationContext(model);
Validator.ValidateObject(model, contex);
}
catch (ValidationException exc)
{
Assert.AreEqual(exceptionMessage, exc.Message);
return;
}
}
}
Do I need to use Assert.AreEqual()
in try block too or should it be only in catch block?