創(chuàng)建一個(gè)簡(jiǎn)單的例子
創(chuàng)建一個(gè)被測(cè)試的Project
創(chuàng)建一個(gè)名為BeTestProject 的Project,將確省的Unit1 保存為BeTestUnit.pas文件。把確省的TForm1 改名為BeTestForm 中增加一個(gè)Public 的函數(shù)
BeTestFunction,BeTestFunction 代碼如下:
function BeTestForm.BeTestFunction(i,j:integer):integer;
begin
Result:=i*j;
end;
創(chuàng)建一個(gè)測(cè)試Project
創(chuàng)建新的Project
再創(chuàng)建一個(gè)Project,命名為TestProject。如果沒有和BeTestProject 放在同一目錄,將BeTestProject的存放路徑加到加到菜單Tools>Environment Options 里面的Library->Library Path 中。
編寫TestCase
刪除確省的Unit1(Form1),創(chuàng)建一個(gè)的Unit,注意不是Form.
將創(chuàng)建的Unit 保存為TestUnit,在interface 中加入以下代碼
uses
TestFrameWork,BeTestUnit;
TestFrameWork 是每個(gè)TestCase 都必須使用的,后面要使用的TtestCase 等類的定義都在TestFrameWork 中。BeTestUnit 是將要被測(cè)試單元。
定義TestCase,測(cè)試類定義代碼如下:
TTestCaseFirst = class(TTestCase)
private
BeTestForm : TBeTestForm; //要測(cè)試的類
protected
procedure SetUp; override; //初始化類
procedure TearDown; override; //清除數(shù)據(jù)
published
procedure TestFirst; //第一個(gè)測(cè)試方法
procedure TestSecond; //第二個(gè)測(cè)試方法
end;
在定義測(cè)試方法時(shí)候注意,Dunit 是通過RTTI(RunTime Type Information)來(lái)尋找并自動(dòng)注冊(cè)測(cè)試方面的,具體實(shí)現(xiàn)是通過代碼TestFramework.RegisterTest(TTestCaseFirst.Suite);
這段代碼將在后面提到,TtestCaseFirst.Suit 在尋找的規(guī)則是:
1、測(cè)試方法是沒有參數(shù)的Procedure
2、測(cè)試方法被申明為Published
SetUp,TearDown 是在運(yùn)行測(cè)試方法前、后運(yùn)行的,所有一般把要測(cè)試的類的
初始化及清除放在這兩個(gè)過程中。
以下是實(shí)現(xiàn)的代碼:
procedure TTestCaseFirst.SetUp;
begin
BeTestForm := TBeTestForm.Create(Nil);
end;
procedure TTestCaseFirst.TearDown;
begin
BeTestForm.Destroy;
end;
procedure TTestCaseFirst.TestFirst; //第一個(gè)測(cè)試方法
begin
Check(BeTestForm.BeTestFunction(1,3) = 3,'First Test fail');
end;
procedure TTestCaseFirst.TestSecond; //第二個(gè)測(cè)試方法
begin
Check(BeTestForm.BeTestFunction(1,3)=4,'Second Test fail');
end;
//Register TestCase
initialization
TestFramework.RegisterTest(TTestCaseFirst.Suite);
end.