如何测试测试对象破坏后引用可能导致的内存泄漏(DUnitX,Spring4D 1.2.2)



TMyClass包含两个引用。对CCD_ 2的引用和对IMyInterface的引用。对IList<integer>的嘲讽是没有必要的。这个框架可能经过了很好的测试,可以很好地预测行为,所以我可以把它看作一个Data对象。但是IMyInterface是一个未经测试的服务,所以我应该在单元测试中嘲笑它。我想检查内存泄漏,所以我想测试主题销毁后引用的RefCount-s的修改。IList<integer>的"RefCount"以正确的方式更改。但我不能对嘲笑的IMyInterface(在我的解决方案中(说同样的话。如何测试引用是否不会导致内存泄漏?或者像这样的测试是集成测试,我应该总是用真实的实例来测试它吗?

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.

Memorylak检查不需要显式完成-我建议使用https://github.com/shadow-cs/delphi-leakcheck为此,它可以与DUnit或DUnitX无缝集成,并在发生泄漏时自动为您提供所需的所有信息(而不是只告诉您"存在x字节的泄漏",DUnit只需在运行测试前后简单地比较分配的字节即可做到这一点(

最新更新