File |
Description |
TestFramework.pas | The framework itself. |
TestExtensions.pas | Decorator classes that may be used to extend testcases. |
GUITesting.pas | Classes for testing user interfaces (Forms and Dialogs). |
TextTestRunner.pas | Routines to run tests in console mode. |
GUITestRunner.pas | The graphical user interface to the framework.. |
GUITestRunner.dfm | The GUITestRunner Form |
Dunit 基本實現方法(GUI 方式)
Dunit 的基本實現思路是將被測試代碼(單元)與測試代碼(單元)分開。提供一個FrameWork 及一個運行界面。所有的測試單元都應繼承TtestCase。
運行GUI 界面
運行TestCase
這里要注意的一點是SetUp 方法和TearDown 是每個測試方法運行時都被調用的,如果想要只運行一次Setup 及TearDown,應該使用TtestSetup 類,具體情況后面《Dunit 附加功能》一節。
創建一個簡單的例子
創建一個被測試的Project
創建一個名為BeTestProject 的Project,將確省的Unit1 保存為BeTestUnit.pas文件。把確省的TForm1 改名為BeTestForm 中增加一個Public 的函數
BeTestFunction,BeTestFunction 代碼如下:
function BeTestForm.BeTestFunction(i,j:integer):integer;
begin
Result:=i*j;
end;
創建一個測試Project
創建新的Project
再創建一個Project,命名為TestProject。如果沒有和BeTestProject 放在同一
目錄,將BeTestProject的存放路徑加到加到菜單Tools->Environment Options 里
面的Library->Library Path 中。
編寫TestCase
刪除確省的Unit1(Form1),創建一個的Unit,注意不是Form.
將創建的Unit 保存為TestUnit,在interface 中加入以下代碼
uses
TestFrameWork,BeTestUnit;
TestFrameWork 是每個TestCase 都必須使用的,后面要使用的TtestCase 等
類的定義都在TestFrameWork 中。BeTestUnit 是將要被測試單元。
定義TestCase,測試類定義代碼如下:
TTestCaseFirst = class(TTestCase)
private
BeTestForm : TBeTestForm; //要測試的類
protected
procedure SetUp; override; //初始化類
procedure TearDown; override; //清除數據
published
procedure TestFirst; //第一個測試方法
procedure TestSecond; //第二個測試方法
end;
在定義測試方法時候注意,Dunit 是通過RTTI(RunTime Type Information)來
尋找并自動注冊測試方面的,具體實現是通過代碼
TestFramework.RegisterTest(TTestCaseFirst.Suite);
這段代碼將在后面提到,TtestCaseFirst.Suit 在尋找的規則是:
1、測試方法是沒有參數的Procedure
2、測試方法被申明為Published
SetUp,TearDown 是在運行測試方法前、后運行的,所有一般把要測試的類的
初始化及清除放在這兩個過程中。
以下是實現的代碼:
procedure TTestCaseFirst.SetUp;
begin
BeTestForm := TBeTestForm.Create(Nil);
end;
procedure TTestCaseFirst.TearDown;
begin
BeTestForm.Destroy;
end;
procedure TTestCaseFirst.TestFirst; //第一個測試方法
begin
Check(BeTestForm.BeTestFunction(1,3) = 3,'First Test fail');
end;
procedure TTestCaseFirst.TestSecond; //第二個測試方法
begin
Check(BeTestForm.BeTestFunction(1,3)=4,'Second Test fail');
end;
//Register TestCase
initialization
TestFramework.RegisterTest(TTestCaseFirst.Suite);
end.
Check 是TestCase 類提供的一個方法。以下是TestCase 的實現代碼:
如果Check 沒有通過的話,Dunit 將報錯。錯誤提示就在第二個參數中定義,
其他有關類及方法的定義請看連機文檔,文檔放在Dunit 安裝目錄\doc\API\IDH_Library_DUnit_-_Xtreme_Unit_Testing_for_Delphi.htmInitialzation 代碼完成測試單元的注冊。
修改Project 主文件
運行前的最后一步是修改Project 主文件TestProject.dpr。先使用菜單
Project->View Source 打開TestProject.dpr.
修改后的代碼如下:
program TestProject;
uses
Forms,
TestFrameWork,
GUITestRunner,
TestUnit in 'TestUnit.pas';
{$R *.res}
begin
Application.Initialize;
//Application.Run;
GUITestRunner.RunRegisteredTests;
end.
上面的加粗代碼是要增加和修改。
原文轉自:http://www.anti-gravitydesign.com