[英]Delphi Unit Testing : Writing a simple spy for the CUT
我正在尋找一種簡便 , 簡潔地為Delphi下的DUnitX測試框架編寫間諜的方法。
過去,我使用過非常丑陋的方法:
[TestFixture]
Test = class(TObject)
public
[test]
procedure Test1;
end;
TMyClass = class(TObject)
protected
procedure MyProcedure; virtual;
end;
TMyTestClass = class(TMyClass)
protected
fMyProcedureCalled : Boolean;
procedure MyProcedure; override;
end
procedure TMyTestClass.MyProcedure;
begin
fMyProcedureCalled := true;
inherited;
end;
procedure Test.Test1;
var aObj : TMyTestClass;
begin
TMyTestClass.Create;
Assert.IsTrue(aObj.fMyProcedureCalled);
end;
所有這些代碼可檢查是否調用了過程。 太冗長了!
有沒有辦法寫間諜來幫助我減少代碼?
聽起來像是一個模擬的用例(我在這里使用了模擬一詞,因為大多數框架將它們的各種測試雙精度模型稱為模擬)。
在下面的示例中,我使用的是DUnit,但對於DUnitX來說應該沒有任何區別。 我也在使用Spring4D 1.2中的模擬功能(我沒有檢查Delphi Mocks是否支持此功能)
unit MyClass;
interface
type
TMyClass = class
private
fCounter: Integer;
protected
procedure MyProcedure; virtual;
public
property Counter: Integer read fCounter;
end;
implementation
procedure TMyClass.MyProcedure;
begin
Inc(fCounter);
end;
end.
program Tests;
uses
TestFramework,
TestInsight.DUnit,
Spring.Mocking,
MyClass in 'MyClass.pas';
type
TMyClass = class(MyClass.TMyClass)
public
// just to make it accessible for the test
procedure MyProcedure; override;
end;
TMyTest = class(TTestCase)
published
procedure Test1;
end;
procedure TMyClass.MyProcedure;
begin
inherited;
end;
procedure TMyTest.Test1;
var
// the mock is getting auto initialized on its first use
// and defaults to TMockBehavior.Dynamic which means it lets all calls happen
m: Mock<TMyClass>;
o: TMyClass;
begin
// set this to true to actually call the "real" method
m.CallBase := True;
// do something with o
o := m;
o.MyProcedure;
// check if the expected call actually did happen
m.Received(Times.Once).MyProcedure;
// to prove that it actually did call the "real" method
CheckEquals(1, o.Counter);
end;
begin
RegisterTest(TMyTest.Suite);
RunRegisteredTests();
end.
請記住,盡管這僅適用於虛擬方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.