c# - 我如何告诉抽象类的模拟/ stub 使用它对 Object.Equals() 的覆盖?

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

我有一个相对简单的抽象类。对于这个问题,我进一步简化了它。

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

最佳答案

当然,我在发布问题后就想通了......

我不知道这样做是否正确,但它似乎有效。我告诉 stub .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));
}

关于c# - 我如何告诉抽象类的模拟/ stub 使用它对 Object.Equals() 的覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9746309/

相关文章:

r - 仅测试 R 脚本中的单个函数

c# - 调用函数的设置方法

c# - 使用正则表达式从字符串中提取数字

c# - 在循环中获取 Null 异常错误。尝试调试

C#:在与相关类相同的 .cs 文件中取消嵌套结构?

c# - 委托(delegate)会导致内存泄漏吗? GC.TotalMemory(true) 似乎表明如此

python - 猴子修补从子方法调用的函数中的类 (Python)

python - 模拟 timedelta.total_seconds()

c# - 无法加载 Entity Framework 提供程序类型?

c# - 在异步单元测试中调用 Assert.Inconclusive() 被报告为失败