c# - IndexOf find no element in a List<> while Mock -
i have list of object below
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, keep simple name = "someone", age = 18}); person eighteenyearsold = _checkage.findeighteenyearsold (personlist); int index = personlist.indexof (eighteenyearsold); //do return result; } } [testmethod] public void dosomething_test() { //given: //when: 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: }
as have mocked findeighteenyearsold
method returns person
object same states presents in personlist
. when personlist.indexof()
executes returns index -1, suppose 0. should do.
list.indexof
uses equals
find equal objects. if class doesn't override references compared. since 2 instances not same list.indexof
returns -1
.
so override equals
(and gethashcode
then):
public class person { public string name { get; set; } public int age { get; set; } public override bool equals (object obj) { person otherperson = obj person; return otherperson != null && otherperson.name == name && otherperson.age == age; } // http://stackoverflow.com/a/263416/284240 public override int gethashcode() { unchecked // overflow fine, 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; } } }
Comments
Post a Comment