[英]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.
我尝试创建一个模拟,但是当我将模拟作为一个对象并调用Equals时,它不会在抽象类中调用我的代码。 It just immediately returns false.
它只是立即返回false。 Same if I add it to a list of object and call .Remove or .Contains on the list;
如果我将它添加到对象列表并在列表中调用.Remove或.Contains,则相同; still just returns false without hitting the code in my abstract class.
仍然只返回false,而不是在我的抽象类中遇到代码。
I'm using mstest and rhino mocks. 我正在使用mstest和犀牛嘲笑。
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()
我告诉存根.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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.