我有两个列表,其中包含两个User对象。
列表内的对象的值相同。
但是当我检查此列表时,单元测试返回CollectionAssert.AreEqual失败。 (索引为0的元素不匹配)。
我认为CollectionAssert.AreEqual方法不会检查列表的值,而是检查引用。
我的问题是如何比较单元测试中的两个列表的值?
public class User
{
public string Name { get; set; }
public string Password { get; set; }
}
[TestMethod]
public void CheckUserList()
{
List<User> users = new List<User>()
{
new User(){ Name="Name",Password="Pass"},
new User(){ Name="Name1",Password="Pass1"},
new User(){ Name="Name2",Password="Pass2"},
};
List<User> users1 = new List<User>()
{
new User(){ Name="Name",Password="Pass"},
new User(){ Name="Name1",Password="Pass1"},
new User(){ Name="Name2",Password="Pass2"},
};
CollectionAssert.AreEqual(users, users1);
}
答案 0 :(得分:1)
我认为您需要为==
类重写Equals()
运算符或User
方法。
public class User
{
public string Name { get; set; }
public string Password { get; set; }
public override bool Equals(object obj)
{
if (obj is User another)
{
return Name == another.Name && Password == another.Password;
}
return base.Equals(obj);
}
public static bool operator ==(User left, User right)
{
return left.Equals(right);
}
public static bool operator !=(User left, User right)
{
return !left.Equals(right);
}
}
答案 1 :(得分:0)
足够Equal和GetHashCode方法。然后CollectionAssert.AreEqual将按预期工作
public class User
{
public string Name { get; set; }
public string Password { get; set; }
public override bool Equals(object obj)
{
var user = obj as User;
return user != null &&
Name == user.Name &&
Password == user.Password;
}
public override int GetHashCode()
{
var hashCode = 1290039854;
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Password);
return hashCode;
}
}