2016-05-09 16 views
0

我有像下面的IndexOf發現沒有元件在一個列表<>而模擬

public class Person 
{ 
    public string Name {get; set;} 
    public int Age {get; set;} 
} 
public class SomeClass 
{ 
public int DoSomething() 
{ 
    int result; 
    List<Person> personList = new List<Person>(); 
    personList.Add(new Person { //with 1 object, just to keep simple 
     Name = "Someone", 
     Age = 18}); 
    Person eighteenYearsOld = _checkAge.FindEighteenYearsOld (personList); 
    int index = personList.IndexOf (eighteenYearsOld); 
    //do something 
    return result; 
} 
} 
[TestMethod] 
public void DoSomething_Test() 
{ 
    //Given: 

    //When: I call SomeClass object 
    Person eightnneYears = new Person { 
     Name = "Someone", 
     Age = 18}; 
    _mockCheckAge.Setup (x => x.FindEighteenYearsOld(It.IsAny<List<Person>>())).Returns(eightnneYears); 
    _someClass = new SomeClass (_mockCheckAge.Object); 
    int result = _someClass.DoSomething(); 
    //Then: 
} 

對象的列表正如我嘲笑FindEighteenYearsOld方法返回與相同狀態的Person對象,它是在personList禮物。但是當personList.IndexOf()執行時,它返回索引-1,假設爲0.我應該怎麼做。

+3

你'Person'類沒有重載'Equals',其中'IndexOf'用它來查找相同的值。 –

+0

爲什麼有'FindEighteenYearsOld'方法而不是'FindByAge(18)'? – user3791372

回答

2

List.IndexOf使用Equals找到相同的對象。如果你的班級不覆蓋它,只有引用進行比較。由於你的兩個實例不一樣List.IndexOf返回-1

所以覆蓋Equals(也總是GetHashCode則):

public class Person 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 

    public override bool Equals (Object obj) 
    { 
     Person otherPerson = obj as Person; 
     return otherPerson != null 
      && otherPerson.Name == Name 
      && otherPerson.Age == Age; 
    } 

    // http://stackoverflow.com/a/263416/284240 
    public override int GetHashCode() 
    { 
     unchecked // Overflow is fine, just wrap 
     { 
      int hash = 17; 
      hash = hash * 23 + (Name?.GetHashCode() ?? 0); // or: hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode()); 
      hash = hash * 23 + Age; ; 
      return hash; 
     } 
    } 
} 
相關問題