請參閱下面的代碼:應用GetProperties,用於接口只
public static class AssertEx
{
public static void PropertyValuesAreEquals(object actual, object expected)
{
PropertyInfo[] properties = expected.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
object expectedValue = property.GetValue(expected, null);
object actualValue = property.GetValue(actual, null);
if (actualValue is IList)
AssertListsAreEquals(property, (IList)actualValue, (IList)expectedValue);
else if (!Equals(expectedValue, actualValue))
Assert.Fail("Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue);
}
}
private static void AssertListsAreEquals(PropertyInfo property, IList actualList, IList expectedList)
{
if (actualList.Count != expectedList.Count)
Assert.Fail("Property {0}.{1} does not match. Expected IList containing {2} elements but was IList containing {3} elements", property.PropertyType.Name, property.Name, expectedList.Count, actualList.Count);
for (int i = 0; i < actualList.Count; i++)
if (!Equals(actualList[i], expectedList[i]))
Assert.Fail("Property {0}.{1} does not match. Expected IList with element {1} equals to {2} but was IList with element {1} equals to {3}", property.PropertyType.Name, property.Name, expectedList[i], actualList[i]);
}
}
我把這個從這裏:Compare equality between two objects in NUnit(Juanmas的回答)
說我有一個這樣的接口:
public interface IView
{
decimal ID { get; set; }
decimal Name { get; set; }
}
然後我有兩個這樣的看法:
IView view = new FormMain();
IView view2 = new FormMain();
view和view2然後被賦予屬性。
我那麼想的接口,所以我這樣做比較:
Assert.AreEqual(Helper.PropertyValuesAreEquals(view, view2), true);
然而,這將產生一個例外: 「物業GET方法未找到」
。
我該如何確保此函數只獲取屬性在我的界面中的屬性?
我是否應該單元測試這樣的視圖?
您可以考慮使用泛型,同樣在上面的邏輯中,您應該檢查屬性是否存在於提供的兩個對象中。 – Nkosi