There is little point of testing data annotations, if they are in code hard coded.
but in case you have to:
my model definition:
public class FilterModel
{
///
/// Apply filter from date.
///
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[Display(Name = "From date")]
public DateTime FromDate { get; set; }
///
/// Apply filter to date.
///
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[Display(Name = "To date")]
public DateTime ToDate { get; set; }
[Display(Name = "Branch")]
public int BranchId { get; set; }
[Display(Name = "Agent")]
public int RsmId { get; set; }
public List Branches { get; set; }
public List Rsms { get; set; }
}
as you can see I have some hard coded display names I would like to test.
///
/// Checks the filter contain correct data annotations.
///
[TestMethod]
public void CheckFilterContainCorrectDataAnnotations()
{
var expectedDisplayName = "From date";
var expectedToDate= "To date";
var expectedBranchName = "Branch";
var expectedAgentName = "Agent";
var fromDateProperty = typeof(FilterModel).GetProperty("FromDate");
var toDateProperty = typeof(FilterModel).GetProperty("ToDate");
var branchProperty = typeof(FilterModel).GetProperty("BranchId");
var agentProperty = typeof(FilterModel).GetProperty("RsmId");
var fromDateActualName = GetDisplayName(fromDateProperty);
var actualToDate = GetDisplayName(toDateProperty);
var actualBranchName = GetDisplayName(branchProperty);
var actualAgentName = GetDisplayName(agentProperty);
Assert.AreEqual(expectedDisplayName,fromDateActualName);
Assert.AreEqual(expectedToDate, actualToDate);
Assert.AreEqual(expectedAgentName, actualAgentName);
Assert.AreEqual(expectedBranchName, actualBranchName);
}
Here is my test method to get data using data annotation.
///
/// Gets the display name.
///
/// The property.
/// String of the property name
public static string GetDisplayName(PropertyInfo property)
{
Object[] displayAttributes = property.GetCustomAttributes(typeof(DisplayAttribute), true);
if (displayAttributes.Length == 1)
return ((DisplayAttribute)displayAttributes[0]).Name;
return property.Name.ToString(CultureInfo.InvariantCulture);
}
No comments:
Post a Comment