Rhino.Mocks 在返回多态对象时产生 InvalidCastException
我是第一次使用Rhino.Mocks 3.6。我正在尝试为返回继承类型(B)的接口创建一个存根。当我尝试这样做时,它将生成一个 InvalidCastException
尝试将某些代理对象转换为基类 (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();
在我看来,问题在于它生成的代理类不具有与现有类相同的继承结构。然而,在我看来,返回方法签名指定类型的子类是一种相当常见的情况。
我尝试了一些变体,但无法使其发挥作用。有什么想法吗?
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).
For example:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
mocks.Record
设置模拟对象,使用mocks.PlayBack
运行测试。Use
mocks.Record
to set up your mocked objects, usemocks.PlayBack
to run your tests.