【问题标题】:How do I tell my mock/stub of an abstract class to use its override of Object.Equals()?如何告诉抽象类的模拟/存根使用其对 Object.Equals() 的覆盖?
【发布时间】:2012-03-17 00:54:27
【问题描述】:

我有一个相对简单的抽象类。我已经为这个问题进一步简化了。

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);
    }
}

我试图弄清楚如何编写单元测试以确保对象等于覆盖工作。我尝试创建一个模拟,但是当我将模拟转换为一个对象并调用 Equals 时,它不会在抽象类中调用我的代码。它只是立即返回 false。如果我将它添加到对象列表并在列表中调用 .Remove 或 .Contains ,则相同;仍然只是返回 false 而不点击我的抽象类中的代码。

我正在使用 mstest 和 rhino 模拟。

为了完整起见,这是一个我希望可以工作但没有成功的测试:

[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));
}

【问题讨论】:

    标签: c# unit-testing mstest rhino-mocks equals


    【解决方案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));
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-25
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多