简体   繁体   中英

How do I tell my mock/stub of an abstract class to use its override of Object.Equals()?

I have a relatively simple abstract class. I've simplified it further for this question.

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

I'm trying to figure out how to write a unit test to ensure the object equals override works. I tried creating a mock, but when I cast the mock as an object and call Equals, it doesn't call my code in the abstract class. It just immediately returns false. Same if I add it to a list of object and call .Remove or .Contains on the list; still just returns false without hitting the code in my abstract class.

I'm using mstest and rhino mocks.

For completeness, here is a test that I would expect to work but doesn't:

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

Of course, I figured it out right after I post the question...

I don't know if this is the correct way to do this, but it seems to be working. I told the 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM