8

我正在阅读测试驱动开发:示例。所有示例都使用 Java 和 Junit(我在第 10 章)。有一种测试方法可以测试两个对象是否相等。我已经覆盖了该类的 Equals 但是在运行我的测试时它失败了。

这是示例代码

public class BaseX
{
    public string Test { get; set; }

    public override bool Equals(object obj)
    {
        return this.Test == ((BaseX)obj).Test;
    }

    public override string ToString()
    {
        return string.Format("Tyep: {0}, Test: {1}", this.GetType().Name, this.Test);
    }
}

public class A : BaseX
{

}

这是我的测试代码

[Fact]
public void FunTest2()
{
    var b1 = new BaseX();
    var a1 = new A();

    b1.Test = "a";
    a1.Test = "a";

    Assert.Equal(a1, b1);
}

当我运行测试时,它将失败并显示此消息。

TDD1.UnitTest.UnitTest1.FunTest2 : Assert.Equal() Failure
Expected: Tyep: A, Test: a
Actual:   Tyep: BaseX, Test: a

我认为Assert.Equal比较对象的值和类型。所以,我查看了 xunit 代码并找到了那个Assert.Equalcall IEqualityComparer.Equals。如果我想用覆盖方法比较两个对象,我应该使用什么方法?

更新
我在Windows 7Visual Studio 11 Betaxunit.net 1.9.0.1566上测试(从 nuget 获取文件)

4

1 回答 1

7

Before comparing both objects using T's Equals method, xunit compares types:

// Same type?
if (!skipTypeCheck && x.GetType() != y.GetType())
    return false;

As I see it, you have two choices:

The simple choice

Assert.True(b1.Equals(a1));

It might be less expected than an Equal overload, but KISS...

The less simple choice

public class BaseXComparer : IEqualityComparer<BaseX>
{
    public bool Equals(BaseX x, BaseX y)
    {
        return x.Test.Equals(y.Test);
    }

    public int GetHashCode(BaseX obj)
    {
        return obj.Test.GetHashCode();
    }
}

And then:

Assert.Equal(a1, b1, new BaseXComparer());

In this case, consider this.

Until someone will add a new overload (shouldn't be tricky, as the inner implementation has a bool parameter for this) or an extension, I'd recommend using the simple method above.

于 2012-04-29T15:49:19.803 回答