加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何告诉我的抽象类的mock / stub使用它的Object.Equals()

发布时间:2020-12-15 21:31:52 所属栏目:百科 来源:网络整理
导读:我有一个相对简单的抽象类.我已经为这个问题进一步简化了. 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
我有一个相对简单的抽象类.我已经为这个问题进一步简化了.

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和犀牛嘲笑.

为了完整性,这是一个我期望工作的测试,但不是:

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

解决方法

当然,我在发布问题后立即发现了……

我不知道这是否是正确的方法,但它似乎正在起作用.我告诉存根.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));
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读