I am currently testing APIs and I want create a generic validator that will validate the json properties and its values to the Model.
For example I have the following Json response from the server
{
"id" : 1,
"name" : "John",
"age" : 30
}
public class UserDTO
{
public int id { get; set; }
public string name{ get; set; }
public int age { get; set; }
public static UserDTO Userinfo()
{
return new UserDTO()
{
id = 1,
name = "John",
age = 30
};
}
}
What I have tried:
//So I am trying to do here is create a class that will take any Model type class and then have a validate method where it takes the IRestresponse(using Restsharp) and convert to objects, get the properties and values. Then compare that to the Model class.
public class PropertiesValidator<TModel> where TModel : class
{
public void Validate(IRestResponse response, TModel tmodelObj)
{
var content = response.Content;
object acutalObjects = JsonConvert.DeserializeObject(content);
PropertyInfo[] properties = tmodelObj.GetType().GetProperties();
foreach (PropertyInfo modelProperty in properties)
{
PropertyInfo currentExpectedProperty = tmodelObj.GetType().GetProperty(modelProperty.Name);
string exceptionMessage =
string.Format("The property {0} of class {1} was not as expected.", modelProperty.Name, modelProperty.DeclaringType.Name);
Assert.AreEqual(currentExpectedProperty.GetValue(tmodelObj, null), modelProperty.GetValue(acutalObjects, null), exceptionMessage);
}
}