3

使用 Spring 框架中的 Nullable 类型设置 Delphi DSharp 模拟的最佳方法是什么?我尝试了各种方法,我知道我可能遗漏了一些非常基本的东西,但我就是不知道如何让以下代码工作:

program DSharkMockNullable;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  DSharp.Testing.Mock,
  Spring,
  System.SysUtils;

type

  {$M+}
  IBaseMock = interface
  ['{B3311345-3C1F-47E3-8235-57B1BA04E957}']
    function GetId:  TNullableInteger;
    procedure SetId(Value: TNullableInteger);
    property Id: TNullableInteger read GetId write SetId;
  end;

  {$M+}
  IMockMe = interface(IBaseMock)
  ['{07F8F233-E8F5-4743-88C5-97A66BB01E29}']
    function GetObjectId:  TNullableInteger;
    procedure SetObjectId(Value: TNullableInteger);
    property ObjectId: TNullableInteger read GetObjectId write SetObjectId;
    function GetObjectName:  TNullableString;
    procedure SetObjectName(Value: TNullableString);
    property ObjectName: TNullableString read GetObjectName write SetObjectName;
  end;

  TMyObject = class
  public
    function ObjectIdAsString(const AObject: IMockMe): string;
  end;


{ TMyObject }

function TMyObject.ObjectIdAsString(const AObject: IMockMe): string;
var
  LId: Integer;
  LObjectId: Integer;
  LObjectName: string;
begin
  LId := AObject.Id;  // ***** FAILS HERE with an "Invalid Typecast" error
  LObjectId := AObject.ObjectId;
  LObjectName := AObject.ObjectName;
  Result := Format('Id: %d', [LId]);
  Result := Format('Object Id: %d', [LObjectId]);
  Result := Format('Object Name: %s', [LObjectName]);
end;

var
  LMock: Mock<IMockMe>;
  LObject: TMyObject;
begin
  try
    LMock.Setup.WillReturn(123).Any.WhenCalling.Id;
    LMock.Setup.WillReturn(456).Any.WhenCalling.ObjectId;
    LMock.Setup.WillReturn('blahblah').Any.WhenCalling.ObjectName;

    LObject := TMyObject.Create;
    Writeln(LObject.ObjectIdAsString(LMock.Instance));
    LObject.Free;

    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

有什么想法或建议会很棒吗?我正在使用德尔福 XE5。谢谢。瑞克。

4

2 回答 2

6

正确的代码应该是这样的(不使用类型推断):

LMock.Setup.WillReturn<TNullableInteger>(123).Any.WhenCalling.Id;
LMock.Setup.WillReturn<TNullableInteger>(456).Any.WhenCalling.ObjectId;
LMock.Setup.WillReturn<TNullableString>('blahblah').Any.WhenCalling.ObjectName;

除了 Rick 已经在这里给出的正确答案之外,还有一些解释为什么会这样:

原始代码对传递给 WillReturn 的值使用类型推断,并将它们推断为ShortInt, SmallInt(编译器使用适合的最小有符号序数类型)和string. 这些存储为TValue并在调用方法时返回。但是随后 RTTI 尝试将其强制TValue转换为返回类型和失败的方法,因为它不知道如何将 aShortIntSmallIntaNullable<Integer>或 a强制string转换为 a,Nullable<string>因为TValue.TryCast不知道该Nullable<>类型的任何隐式运算符重载并且没有办法注册任何自定义转换器。

于 2014-06-02T06:22:11.750 回答
2

Ok, I should've read "DSharp for Dummies" but any way in case someone else has trouble here is the answer:

LMock.Setup.WillReturn<TNullableInteger>(123).Any.WhenCalling.Id;
LMock.Setup.WillReturn<TNullableInteger>(456).Any.WhenCalling.ObjectId;
LMock.Setup.WillReturn<TNullableString>('blahblah').Any.WhenCalling.ObjectName;

I hope this helps someone else out there ;-)

于 2014-06-02T06:07:39.580 回答