2013-10-24 78 views
1

我目前正在嘗試學習如何使用單元測試,並創建了3個動物對象的實際列表以及3個動物對象的預期列表。問題是我如何斷言檢查列表是否相等?我試過CollectionAssert.AreEqual和Assert.AreEqual,但無濟於事。任何幫助,將不勝感激。斷言比較兩個對象列表C#

的測試方法:

[TestMethod] 
    public void createAnimalsTest2() 
    { 
     animalHandler animalHandler = new animalHandler(); 
     // arrange 
     List<Animal> expected = new List<Animal>(); 
     Animal dog = new Dog("",0); 
     Animal cat = new Cat("",0); 
     Animal mouse = new Mouse("",0); 
     expected.Add(dog); 
     expected.Add(cat); 
     expected.Add(mouse); 
     //actual 
     List<Animal> actual = animalHandler.createAnimals("","","",0,0,0); 


     //assert 
     //this is the line that does not evaluate as true 
     Assert.Equals(expected ,actual); 

    } 
+0

看一看這個問題的答案S.O.的信息:[http://stackoverflow.com/questions/5194966/mstest-collectionassert-areequivalent-failed-the-expected-collection-contains][1] [1]:HTTP://計算器。 com/questions/5194966/mstest-collectionassert-areequivalent-failed-the-expected-collection-contains – Andrew

+0

這工作,但我不能讓你的評論的答案,謝謝你的幫助,我試圖尋找答案,但無法找到它。 – JamesZeinzu

回答

4

只是櫃面有人遇到這樣的未來,得到的答覆是,我不得不創建一個覆蓋,下面的IEqualityComparer描述:

public class MyPersonEqualityComparer : IEqualityComparer<MyPerson> 
{ 
public bool Equals(MyPerson x, MyPerson y) 
{ 
    if (object.ReferenceEquals(x, y)) return true; 

    if (object.ReferenceEquals(x, null)||object.ReferenceEquals(y, null)) return false; 

    return x.Name == y.Name && x.Age == y.Age; 
} 

public int GetHashCode(MyPerson obj) 
{ 
    if (object.ReferenceEquals(obj, null)) return 0; 

    int hashCodeName = obj.Name == null ? 0 : obj.Name.GetHashCode(); 
    int hasCodeAge = obj.Age.GetHashCode(); 

    return hashCodeName^hasCodeAge; 
} 

}

2

這是正確的,因爲列表是包含類似的數據2個不同的對象。

爲了得到比較列表,你應該使用CollectionAssert

CollectionAssert.AreEqual(expected ,actual); 

這應該做的伎倆。

+1

嗯,CollectionAssert.AreEqual不起作用,它說:CollectionAssert.AreEqual失敗。 (索引0處的元素不匹配。) – JamesZeinzu

+0

我明白這可能是因爲即使對象擁有相同的信息,它們也不是同一個對象。是否有不同的方法比較對象內容而不是對象本身? – JamesZeinzu

+2

一旦您使用自定義IComparer和CollectionAssert.AreEqual,它應該可以正常工作。應該是第三個參數。請參閱http://msdn.microsoft.com/de-de/library/vstudio/ms243703.aspx –