如何告诉我模拟/存根一个抽象类使用它的Object.Equals()方法的覆盖?

4
我有一个相对简单的抽象类。我为了这个问题进一步简化了它。
public abstract class BaseFoo
{
    public abstract string Identification { get; }
    //some other abstract methods

    public override bool Equals(object obj)
    {
        BaseFoo other = obj as BaseFoo;
        if(other == null)
        {
            return false;
        }
        return this.Identification.Equals(other.Identification);
    }
}

我正在尝试找出如何编写单元测试来确保对象相等的覆盖工作。我尝试创建一个Mock,但是当我将Mock强制转换为对象并调用Equals时,它不会调用我在抽象类中的代码,而是立即返回false。如果将其添加到对象列表中并调用列表上的.Remove或.Contains,则仍然只返回false,而没有命中我的抽象类中的代码。
我使用mstest和rhino mocks。
为了完整起见,这里是一个我希望能够工作但却没有的测试:
[TestMethod]
public void BaseFoo_object_Equals_returns_true_for_Foos_with_same_Identification()
{
    var id = "testId";
    var foo1 = MockRepository.GenerateStub<BaseFoo>();
    var foo2 = MockRepository.GenerateStub<BaseFoo>();
    foo1.Stub(x => x.Identification).Return(id);
    foo2.Stub(x => x.Identification).Return(id);
    Assert.IsTrue(((object)foo1).Equals(foo2));
}
1个回答

1

当然,在我发布问题后立刻就想到了解决方法...

我不知道这是否是正确的做法,但它似乎有效。我告诉存根 .CallOriginalMethod()。

[TestMethod]
public void BaseFoo_object_Equals_returns_true_for_Foos_with_same_Identification()
{
    var id = "testId";
    var foo1 = MockRepository.GenerateStub<BaseFoo>();
    var foo2 = MockRepository.GenerateStub<BaseFoo>();
    foo1.Stub(x => x.Identification).Return(id);
    foo2.Stub(x => x.Identification).Return(id);
    foo1.Stub(x => ((object)x).Equals(Arg<object>.Is.Anything)).CallOriginalMethod(OriginalCallOptions.NoExpectation);
    Assert.IsTrue(((object)foo1).Equals(foo2));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接