我有一个相对简单的抽象类。对于这个问题,我进一步简化了它。
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/