روشی برای مقایسهی مقادیر تمام خواص دو شیء در آزمونهای واحد
نویسنده: وحید محمدطاهری
تاریخ: ۱۳۹۵/۰۸/۲۴ ۲:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class PropertiesValidator<TK, T> where T : new() where TK : new()
{
static TK _instance;
public static TK Instance
{
get
{
if (_instance == null)
{
_instance = new TK();
}
return _instance;
}
}
public void Validate(T expectedObject, T realObject, params string[] propertiesNotToCompare)
{
var properties = realObject.GetType().GetProperties();
foreach (var currentRealProperty in properties)
{
if (!propertiesNotToCompare.Contains(currentRealProperty.Name))
{
var currentExpectedProperty = expectedObject.GetType().GetProperty(currentRealProperty.Name);
var exceptionMessage = $"The property {currentRealProperty.Name} of class {currentRealProperty.DeclaringType?.Name} was not as expected.";
if (currentRealProperty.PropertyType != typeof(DateTime) && currentRealProperty.PropertyType != typeof(DateTime?))
{
Assert.AreEqual( currentExpectedProperty.GetValue( expectedObject,
null ),
currentRealProperty.GetValue( realObject,
null ),
exceptionMessage );
}
else
{
DateTimeAssert.Validate( currentExpectedProperty.GetValue( expectedObject,
null ) as DateTime?,
currentRealProperty.GetValue( realObject,
null ) as DateTime?,
TimeSpan.FromMinutes( 5 ) );
}
}
}
}
} public class ObjectToAssert
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime LastVisit { get; set; }
} var expectedObject = new ObjectToAssert
{
FirstName = "Vahid",
LastName = "Mohammad Taheri",
LastVisit = new DateTime( 2016, 11, 14, 0, 10, 50 )
};
var actualObject = new ObjectToAssert
{
FirstName = "Vahid",
LastName = "Mohammad Taheri",
LastVisit = new DateTime( 2016, 11, 14, 0, 13, 50 )
}; public class ObjectToAssertValidator : PropertiesValidator<ObjectToAssertValidator, ObjectToAssert>
{
public void Validate(ObjectToAssert expected, ObjectToAssert actual)
{
this.Validate(expected, actual, "FirstName");
}
} ObjectToAssertValidator.Instance.Validate(expectedObject, actualObject);