Rhino.Mocks 在返回多态对象时产生 InvalidCastException [英] Rhino.Mocks produces InvalidCastException when returning polymorphic object
问题描述
我是第一次使用 Rhino.Mocks 3.6.我正在尝试为返回继承类型 (B) 的接口创建存根.当我尝试这样做时,它会生成一个 InvalidCastException
尝试将某个代理对象转换为基类 (A).
I'm using Rhino.Mocks 3.6 for the first time. I'm trying to create a stub for an interface that returns an inherited type (B). When I try to do this, it will generate an InvalidCastException
trying to convert some proxy object to the base class (A).
例如:
class A {}
class B : A {}
interface IMyInterface
{
A GetA();
}
// Create a stub
var mocks = new MockRepository();
var stub = mocks.Stub<IMyInterface>();
Expect.Call( stub.GetA() ).Return( new B() );
// This will throw an InvalidCastException
var myA = stub.GetA();
在我看来,问题在于它生成的代理类与现有类的继承结构不同.但是,在我看来,返回由方法签名指定的类型的子类是一种相当普遍的情况.
It seems to me that the problem is that it's generating proxy classes that do not have the same inheritance structure as the existing classes. However, it seems to me like a fairly common situation to return a subclass of the type specified by the method signature.
我尝试了一些变体,但我无法让它发挥作用.有什么想法吗?
I've tried a few variations, but I can't get this to work. Any ideas?
推荐答案
使用 mocks.Record
设置模拟对象,使用 mocks.PlayBack
运行测试.
Use mocks.Record
to set up your mocked objects, use mocks.PlayBack
to run your tests.
public class A { }
public class B : A { }
public interface IMyInterface
{
A GetA();
}
[TestFixture]
public class RhinoTestFixture
{
[Test]
public void TestStub()
{
// Create a stub
var mocks = new MockRepository();
IMyInterface stub;
using (mocks.Record())
{
stub = mocks.Stub<IMyInterface>();
stub.Expect(x => stub.GetA()).Return((new B()));
}
using (mocks.Playback())
{
var myA = stub.GetA();
Assert.IsNotNull(myA);
}
}
}
这篇关于Rhino.Mocks 在返回多态对象时产生 InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!