如何模拟接口方法调用,如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.