Rhino.Mocks produces InvalidCastException when returning polymorphic object

Deadly 提交于 2020-03-26 06:10:08

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/3102911/rhino-mocks-produces-invalidcastexception-when-returning-polymorphic-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!