最近因工作的關系又再次搞了一些時候的Delphi開發
那從何說起呢?用個具體的例子會更好的說明問題
IAnimal = Interface
procedure Mate
procedure Eat
procedure GiveBirth
End
這個接口定義了每種動物的三個基本功能
TAnimalCare= class
private
FIntf
public
constructor Create(AnIntf
procedure Reproduction
end
TAnimalCare 是處理繁殖的一個類
所以在建立時需要注人一個基於IAnimal的類
有了IAnimal
建立好Test Project後
TestTAnimalCare = class(TTestCase)
strict private
FAnimalCare
public
procedure SetUp
procedure TearDown
published
procedure TestReproduction
end
在SetUp這裡
TAnimalMock = class(TMock
public
procedure Mate
procedure Eat
procedure GiveBirth
end
procedure TestTAnimalCare
begin
FMock
FAnimalCare
Create(FMock)
end
有了TAnimalMock我們已基本滿足了編譯的要求
procedure TestTAnimalCare
begin
// Expectations
FMock
FMock
FMock
FAnimalCare
FMock
end
這些期望是很自然的
TestReproduction
at $
check
Unexpected call to GiveBirth() <—— Don
Expected
Mate()
Eat()
GiveBirth()
Called
GiveBirth() <—— Don
為什麼?看看
procedure TAnimalCare
begin
Fintf
end
原來我們只調用GiveBirth而沒調用Mate()
procedure TAnimalCare
begin
FIntF
FIntF
Fintf
end
再跑下測試
總結
用Dependency Injection
用Mock來實現一個基於IAnimal的類以便測試
IAnimal
unit MyObjects
interface
uses
classes
type
IAnimal = Interface
procedure Mate
procedure Eat;
procedure GiveBirth;
End;
TAnimalCare= class
private
FIntf : IAnimal;
public
constructor Create(AnIntf : IAnimal);
procedure Reproduction;
end;
implementation
{ TAnimalCare }
constructor TAnimalCare
begin
inherited Create;
FintF := AnIntf;
end;
procedure TAnimalCare
begin
FIntF
FIntF
Fintf
end;
end
測試碼如下
unit TestMyObjects;
interface
uses
TestFramework
type
TAnimalMock = class(TMock
public
procedure Mate;
procedure Eat;
procedure GiveBirth;
end;
TestTAnimalCare = class(TTestCase)
strict private
FMock : TAnimalMock;
FAnimalCare: TAnimalCare;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestReproduction;
end;
implementation
procedure TestTAnimalCare
begin
FMock := TAnimalMock
FAnimalCare := TAnimalCare
end;
procedure TestTAnimalCare
begin
FAnimalCare
FAnimalCare := nil;
FMock
FMock := nil;
end;
procedure TestTAnimalCare
begin
// Expectations
FMock
FMock
FMock
FAnimalCare
FMock
end;
{ TAnimalMock }
procedure TAnimalMock
begin
self
end;
procedure TAnimalMock
begin
self
end;
procedure TAnimalMock
begin
self
end;
initialization
RegisterTest(TestTAnimalCare
end
From:http://tw.wingwit.com/Article/program/Delphi/201311/8431.html