gpt4 book ai didi

.net - 单元测试 Assert.AreEqual 失败

转载 作者:行者123 更新时间:2023-12-04 02:38:12 24 4
gpt4 key购买 nike

我对从集合中获取对象的方法进行了单元测试。这一直失败,我不明白为什么,所以我在下面创建了一个非常简单的测试来创建 2 个供应商对象并测试它们是否相等,看看我是否可以在我的代码测试中发现问题。但是这个测试又失败了。谁能看到或解释为什么?

    [TestMethod()]
public void GetSupplierTest2()
{
Supplier expected = new Supplier();
expected.SupplierID = 32532;
expected.SupplierName = "Test 1"

Supplier actual = new Supplier();
actual.SupplierID = 32532;
actual.SupplierName = "Test 1"

Assert.AreEqual(expected, actual);
}

但是如果我测试测试通过的对象的各个属性......
    [TestMethod()]
public void GetSupplierTest2()
{
Supplier expected = new Supplier();
expected.SupplierID = 32532;
expected.SupplierName = "Test 1"

Supplier actual = new Supplier();
actual.SupplierID = 32532;
actual.SupplierName = "Test 1"

Assert.AreEqual(expected.SupplierID , actual.SupplierID );
Assert.AreEqual(expected.SupplierName , actual.SupplierName );
}

最佳答案

如果您想比较供应商的两个不同实例,并希望在某些属性具有相同值时将它们视为相等,则必须覆盖 Equals方法在 Supplier并在方法中比较这些属性。

您可以在此处阅读有关 Equals 方法的更多信息:http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx

示例实现:

public override bool Equals(object obj)
{
if (obj is Supplier)
{
Supplier other = (Supplier) obj;
return Equals(other.SupplierID, this.SupplierID) && Equals(other.SupplierName, this.SupplierName);
}
return false;
}

请注意,您还会收到编译器警告,提示您还必须实现 GetHashCode,这可能很简单:
public override int GetHashCode()
{
return SupplierID;
}

关于.net - 单元测试 Assert.AreEqual 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6328218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com