delphimockingassignspring4d

Spring4D Mock error when assigning interface


With the these declarations:

type
  IMyIfc = interface(IInvokable)
    ['{11D3AAF1-7A3E-45CA-9FB4-090010A29FC5}']
    function Test: integer;
  end;

  IMySecondIfc = interface(IInvokable)
    ['{3360E5DB-6EDD-4F6E-A8C5-B2FB0ED7C0CD}']
    function GetTestProp: IMyIfc;
    procedure SetTestProp(const Value: IMyIfc);
    property TestProp: IMyIfc read GetTestProp write SetTestProp;
  end;

I try the following, with error on the marked line:

var
    myIfcMock: Mock<IMyIfc>;
    mySecondIfcMock: Mock<IMySecondIfc>;
    mySecondIfc: IMySecondIfc;
    testIfc: IMyIfc;

  myIfcMock.Setup.Returns(5).When.Test;
  mySecondIfcMock.Setup.Returns(myIfcMock).When.TestProp;
  mySecondIfc := mySecondIfcMock;
  testIfc := mySecondIfc.TestProp; // EConvertError with message 'Mock<Unit1.IMyIfc> cannot be converted to IMyIfc'
  ShowMessage(testIfc.Test.ToString);

This seems odd as the mock is in a way implementing the interface. I can't find a way around the problem either. Would be grateful for any hint.


Solution

  • This is a result of using type inference on this line:

    mySecondIfcMock.Setup.Returns(myIfcMock).When.TestProp;
    

    which the compiler actually interprets as:

    mySecondIfcMock.Setup.Returns<Mock<IMyIfc>>(myIfcMock).When.TestProp;
    

    although you actually meant this:

    mySecondIfcMock.Setup.Returns<IMyIfc>(myIfcMock).When.TestProp;
    

    When using 1.2 this is actually what you need to write to make the type conversion (well in fact then there is none because the type already matches).

    In 2.0 (develop) the conversion of Mock<T> -> T has been implemented so you can use type inference there.