我对从集合中获取对象的方法进行了单元测试。这一直失败,我不明白为什么,所以我在下面创建了一个非常简单的测试来创建 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 );
}
正如其他所有答案所说,问题是您正在尝试比较以下实例Supplier
[可能]没有覆盖Equals
方法。但我认为你不应该覆盖Equals
用于测试目的因为它可能会影响生产代码或者您可能需要另一个Equals
生产代码中的逻辑。
相反,您应该像在第一个示例中那样逐一断言每个成员(如果您没有很多地方想要比较整个对象),或者将此比较逻辑封装在某个类中并使用此类:
static class SupplierAllFieldsComparer
{
public static void AssertAreEqual(Supplier expected, Supplier actual)
{
Assert.AreEqual(expected.SupplierID , actual.SupplierID );
Assert.AreEqual(expected.SupplierName , actual.SupplierName );
}
}
// 测试代码:
SupplierAllFieldsComparer.AssertAreEqual(expected, actual);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)