Rhino.Mocks 在返回多态对象时产生 InvalidCastException

发布于 2024-09-06 21:48:24 字数 548 浏览 2 评论 0原文

我是第一次使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

女中豪杰 2024-09-13 21:48:24

使用 mocks.Record 设置模拟对象,使用 mocks.PlayBack 运行测试。

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

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);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文