SORU
25 Kasım 2008, Salı


NUnit iki nesne arasındaki eşitlik karşılaştırın

Bir nesne olduğunu iddia etmeye çalışıyorum "eşit" bir nesne.

Nesneleri Sadece ortak bir takım özellikleri olan bir sınıf örneği. Kolay bir yol NUnit özelliklerine göre eşitliği savunmak için var mı?

Bu benim geçerli çözüm ama daha iyi bir şey olabilir bence

Assert.AreEqual(LeftObject.Property1, RightObject.Property1)
Assert.AreEqual(LeftObject.Property2, RightObject.Property2)
Assert.AreEqual(LeftObject.Property3, RightObject.Property3)
...
Assert.AreEqual(LeftObject.PropertyN, RightObject.PropertyN)

Gidiyorum ne CollectionEquivalentConstraint iki koleksiyon içeriğini aynı NUnit doğrular onda aynı ruhu olurdu.

CEVAP
25 Kasım 2008, Salı


Eğer herhangi bir nedenle Eşittir kılabilirsiniz eğer, yansıma ile ortak özellikleri arasında dolaşır yardımcı bir yöntem oluşturmak ve her özellik onaylayabilirsiniz. Şöyle bir şey:

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]);
    }
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Makeup Lover

    Makeup Lover

    12 HAZİRAN 2011
  • sdasmarchives

    sdasmarchive

    2 HAZİRAN 2010
  • WOSU Public Media

    WOSU Public

    23 AĞUSTOS 2007