UPDATED:
when i executing Unit Test project and then it will return Was unhandled This test result also contained an inner exception instead of “Assert.IsTrue failed. The Description field is required.” Result like (0 Pass, 1 FAIL, 1 Total) but we are not getting any exception at all if i debug with F11
[TestMethod]
[Asynchronous]
[Description("Determines whether the selected or single property is valide using the validation context or validate single properties.")]
public void ValidateSigleWithDataAnnotation()
{
LookupsServices lookupsservices = new LookupsServices();
Lookups lookups = new Lookups() { Description = "", LookupReference = 2, DisplayOrder = 50};
lookupsservices.Lookups.Add(lookups);
//THIS IS NOT WORKING
string message = ValidateProperties.ValidateSingle(lookups, "Description");
Assert.IsTrue(message.Equals(""), message);
//THIS IS WORKING
var results = new List<ValidationResult>();
Validator.TryValidateProperty(lookups.Description , new ValidationContext(lookups, null, null) { MemberName = "Description" }, results);
Assert.IsTrue(results.Count == 0, results[0].ToString());
}
Following is the Generic function to validate individual property
public static string ValidateSingle<T>(T t, string PeropertyName) where T : class
{
string errorMessage = "";
var ValidationMessages = new List<ValidationResult>();
bool ValidationResult = Validator.TryValidateProperty(typeof(T).GetProperty(PeropertyName).Name, new ValidationContext(t, null, null) { MemberName = PeropertyName} , ValidationMessages);
if (!ValidationResult) errorMessage += string.Format("\n{0}", ValidationMessages[0]);
return errorMessage;
}
Following is the Model where Description field id Required
public class Lookups
{
public Lookups() { }
[Key]
public virtual int LookupReference { get; set; }
[Required]
public virtual string Description { get; set; }
public virtual int? DisplayOrder { get; set; }
}
I am getting error “The Description field is required” if i am validating without Generic method, but why am not getting same error using Generic method?
Please Help me…..
Compare these two calls:
In the first form, you’re passing in the name of the property, i.e. “Description”. In the second form, you’re passing in the value of the property, i.e. “”. To make the first call look like the second, you’d need:
It’s not entirely clear to me whether that’s what you want (I haven’t used
Validatormyself) but it may be the answer.