How to Compare two objects in unit test?

前端 未结 15 1705
自闭症患者
自闭症患者 2020-11-30 03:15
public class Student
{
    public string Name { get; set; }
    public int ID { get; set; }
}

...

var st1 = new Student
{
    ID =          


        
15条回答
  •  被撕碎了的回忆
    2020-11-30 03:27

    You should provide an override of Object.Equals and Object.GetHashCode:

    public override bool Equals(object obj) {
        Student other = obj as Student;
        if(other == null) {
            return false;
        }
        return (this.Name == other.Name) && (this.ID == other.ID);
    }
    
    public override int GetHashCode() {
        return 33 * Name.GetHashCode() + ID.GetHashCode();
    }
    

    As for checking if two collections are equal, use Enumerable.SequenceEqual:

    // first and second are IEnumerable
    Assert.IsTrue(first.SequenceEqual(second)); 
    

    Note that you might need to use the overload that accepts an IEqualityComparer.

提交回复
热议问题