簡體   English   中英

如何在 DUnitX 和 Spring4D 1.2.2 中使用 var 參數模擬方法調用

[英]How can I mock a method call with var parameter in DUnitX and Spring4D 1.2.2

如何模擬接口方法調用,如procedure foo( var i_: integer ) 測試方法局部變量作為 var 參數傳遞,因此測試必須使用 Arg.IsAny(測試不訪問它)。 結果值與 var 參數的 out 值不同,因為被測試的方法在返回結果之前對其進行了一些處理。 注釋的When測試中的變體無法編譯時。 當前編譯但產生一個未定義的值(模擬Executes根本不調用,因為 var=pointer 值不匹配)。 如何模擬帶有var參數的方法調用?

unit Unit1;

interface

uses
    DUnitX.TestFramework
  , Spring.Mocking
  ;

type
  IMyInterface = interface ( IInvokable )
    ['{606BA1D8-EAEC-42CB-A774-911628FD2E6C}']
    procedure foo( var x_ : integer );
  end;

  TMyClass = class
    private
      fMyInterface : IMyInterface;
    public
      constructor Create( myInterface_ : IMyInterface );
      function bar : integer;
  end;

  [TestFixture]
  TMyClassUnitTest = class
    public
      [Test]
      procedure bar;
  end;

implementation

constructor TMyClass.Create( myInterface_ : IMyInterface );
begin
  inherited Create;
  fMyInterface := myInterface_;
end;

function TMyClass.bar : integer;
var
  i : integer;
begin
  fMyInterface.foo( i );
  result := i + 1;
end;

procedure TMyClassUnitTest.bar;
var
  myInterfaceMock : Mock<IMyInterface>;
  myClass : TMyClass;
  i : integer;

  procedure prepareMyInterfaceFooCall( fooVarValue_ : integer );
  var
    ii : integer;
  begin
    ii := 7;
    myInterfaceMock.Setup.Executes(

      function ( const args_ : TCallInfo ) : TValue
      begin
        args_[0] := TValue.From<integer>( fooVarValue_ );
      end

    //).When.foo( Arg.IsAny<integer> );
    //).When.foo( integer( Arg.IsAny<integer> ) );
    ).When.foo( ii );
  end;

begin
  prepareMyInterfaceFooCall( 5 );
  myClass := TMyClass.Create( myInterfaceMock );
  try
    i := myClass.bar;
  finally
    FreeAndNIL( myClass );
  end;
  Assert.AreEqual( 6, i );
end;

end.

1.2.2 不能這樣做,但 2.0 可以(目前正在開發分支)

這是您的代碼的相關更改:

procedure prepareMyInterfaceFooCall(expectedValue: Integer);
begin
  myInterfaceMock.Setup.Executes
  // put the wildcard matcher because your code passes a non initialized variable
  // a matcher on the When() always has priority over any individual parameter matching
  .When(Args.Any)
  // use the Arg.Ref syntax specifying the return value
  .foo(Arg.Ref<Integer>(expectedValue).Return);
end;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM