[英]Delphi Mocks lifecycle in DUnit
我想測試最簡單的情況:測試模擬策略對象。 (請參閱:策略模式)。
如果我在TTestCase.setUp
方法中創建一個TMock<T>
並將其存儲在TTestCase
實例屬性中,那么我是否應該在tearDown
方法中釋放/ TTestCase
模擬變量?
mock := NIL
無法編譯:
[dcc32錯誤] TestUnit2.pas(44):E2010不兼容的類型:'Delphi.Mocks.TMock <T>'和'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;
您應該始終清除在設置過程中在TearDown中創建的所有內容。 即使事后可能會進行清理,這也是一個好習慣,它將使您能夠在進行單元測試時查找資源泄漏。
因為TMock<T>
是內部保存接口的記錄,所以您需要確保在測試運行后將其清除,盡管它們可能被下一次SetUp覆蓋或在測試用例實例被銷毀時被覆蓋。
那就是.Free的目的(盡管源中有注釋)
一旦使用模擬執行更復雜的操作,這一點就變得尤為重要,因為它可能會使測試保持活力或在測試后指向無效的引用。 在測試應用程序結束時,我已經看到一些嚴重的崩潰,這些崩潰沒有清理其模擬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.