【发布时间】:2023-03-15 10:15:01
【问题描述】:
我想测试最简单的情况:测试模拟策略对象。 (查看:策略模式)。
如果我在TTestCase.setUp 方法中创建TMock<T> 并将其存储在TTestCase 实例属性中,那么我应该在tearDown 方法中释放/NIL 模拟变量吗?
mock := NIL 无法编译:
[dcc32 错误] TestUnit2.pas(44): E2010 不兼容的类型:'Delphi.Mocks.TMock
' 和 'Pointer'。
mock.free 运行时没有任何错误,但我不确定是否应该调用它。当进程退出其作用域(在测试用例析构函数之后)时释放的模拟。
我应该调用/设置什么吗?
代码:
Unit2.pas:
unit Unit2;
interface
type
TPartClass = class
public
function foo( x_ : integer ) : integer; virtual;
end;
TMainClass = class
private
fPart : TPartClass;
public
constructor create( part_ : TPartClass );
function bar( x_ : integer ) : integer;
end;
implementation
function TPartClass.foo( x_ : integer ) : integer;
begin
result := x_ shl 1;
end;
constructor TMainClass.create( part_ : TPartClass );
begin
inherited create;
fPart := part_;
end;
function TMainClass.bar( x_ : integer ) : integer;
begin
result := fPart.foo( x_ );
end;
TestUnit2.pas:
unit TestUnit2;
interface
uses
Delphi.Mocks, TestFramework, Unit2;
type
TTestTMainClass = class(TTestCase)
strict private
fPartClass : TMock<TPartClass>;
FMainClass: TMainClass;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure Testbar;
end;
implementation
procedure TTestTMainClass.SetUp;
begin
fPartClass := TMock<TPartClass>.create;
FMainClass := TMainClass.Create( fPartClass );
end;
procedure TTestTMainClass.TearDown;
begin
FMainClass.Free;
FMainClass := NIL;
//fPartClass.Free;
//fPartClass := NIL;
end;
procedure TTestTMainClass.Testbar;
var
ReturnValue: Integer;
x_: Integer;
begin
fPartClass.Setup.WillReturn( 10 ).When.foo( 5 );
x_ := 5;
ReturnValue := FMainClass.bar(x_);
checkTRUE( returnValue = 10 );
end;
【问题讨论】:
标签: delphi dunit delphi-mocks