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 t开发者_JAVA百科he 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?
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);
}
}
}
精彩评论