![](/img/trans.png)
[英]How can I mock a method call with var parameter in DUnitX and Spring4D 1.2.2
[英]How to test possible memory leaks caused by references after the destruction of the tested object (DUnitX, Spring4D 1.2.2)
TMyClass
包含兩個引用。 對IList<integer>
的引用和對IMyInterface
的引用。 IList<integer>
的 mocking 不是必需的。 該框架可能經過良好測試,行為可預測,因此我可以將其視為數據 object。 但是IMyInterface
是一個未經測試的服務,所以我應該在單元測試中模擬它。 我想檢查 memory 泄漏,所以我想在主題銷毀后測試引用的 RefCount-s 的修改。 IList<integer>
的“RefCount”以正確的方式變化。 但是對於模擬的IMyInterface
(在我的解決方案中),我不能說同樣的話。 我如何測試參考不會導致 memory 泄漏? 或者像這樣的測試是一個集成測試,我應該總是用真實的實例來測試它嗎?
unit Unit1;
interface
uses
DUnitX.TestFramework
, Spring.Collections
, Spring.Mocking
;
type
IMyInterface = interface ( IInvokable )
['{76B13784-6CCF-4A87-882C-E624F003B082}']
procedure foo;
end;
TMyClass = class
private
fList : IList<integer>;
fMyInterface : IMyInterface;
public
constructor Create( list_ : IList<integer>; myInterface_ : IMyInterface );
end;
[TestFixture]
TMyClassTest = class
protected
function getInterfaceRefCount( const interface_ : IInterface ) : integer;
public
[Test]
procedure listRefCountTest;
[Test]
procedure myInterfaceRefCountTest;
end;
implementation
uses
System.SysUtils
;
constructor TMyClass.Create( list_ : IList<integer>; myInterface_ : IMyInterface );
begin
inherited Create;
fList := list_;
fMyInterface := myInterface_;
end;
function TMyClassTest.getInterfaceRefCount( const interface_ : IInterface ) : integer;
begin
result := ( interface_ as TInterfacedObject ).RefCount;
end;
procedure TMyClassTest.listRefCountTest;
var
list : IList<integer>;
myInterfaceMock : Mock<IMyInterface>;
myClass : TMyClass;
listRefCount : integer;
begin
list := TCollections.CreateList<integer>;
myClass := TMyClass.Create( list, myInterfaceMock );
try
listRefCount := getInterfaceRefCount( list );
finally
FreeAndNIL( myClass );
end;
Assert.AreEqual( listRefCount-1, getInterfaceRefCount( list ) );
end;
procedure TMyClassTest.myInterfaceRefCountTest;
var
list : IList<integer>;
myInterfaceMock : Mock<IMyInterface>;
myClass : TMyClass;
myInterfaceRefCount : integer;
begin
list := TCollections.CreateList<integer>;
myClass := TMyClass.Create( list, myInterfaceMock );
try
myInterfaceRefCount := getInterfaceRefCount( myInterfaceMock.Instance );
finally
FreeAndNIL( myClass );
end;
Assert.AreEqual( myInterfaceRefCount-1, getInterfaceRefCount( myInterfaceMock.Instance ) );
end;
initialization
TDUnitX.RegisterTestFixture(TMyClassTest);
end.
內存泄漏檢查不需要明確進行 - 我建議使用https://github.com/shadow-cs/delphi-leakcheck - 它可以與 DUnit 或 DUnitX 無縫集成,並自動為您提供所需的所有信息當發生泄漏時(與僅告訴您“存在 x 字節泄漏”相反,開箱即用的 DUnit 通過簡單地比較運行測試之前和之后分配的字節來實現)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.