单元测试Assert.AreEqual失败

sug*_*982 10 .net unit-testing assert mstest

我有一个单元测试,用于从集合中获取对象的方法.这一直在失败,我不明白为什么,所以我在下面创建了一个非常简单的测试来创建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);
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我测试测试通过的对象的各个属性...

    [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 );
    }
Run Code Online (Sandbox Code Playgroud)

Sno*_*ear 22

正如其他所有答案都说的那样,问题在于你试图在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 );            
    }
}
Run Code Online (Sandbox Code Playgroud)

//测试代码:

SupplierAllFieldsComparer.AssertAreEqual(expected, actual);
Run Code Online (Sandbox Code Playgroud)

  • 我完全同意.我建议阅读这篇:http://stackoverflow.com/questions/1180044/should-one-override-equals-method-for-asserting-the-object-equality-in-a-unit-tes (2认同)

Bub*_*rap 4

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

您可以在此处阅读有关 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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,您还会收到编译器警告,提示您还必须实现 GetHashCode,这可能很简单:

public override int GetHashCode()
{
    return SupplierID;
}
Run Code Online (Sandbox Code Playgroud)