CodeIgniter 使用手冊版本 2.1.4


單元測試類別

單元測試是為應用軟體中每一個函數撰寫測試程式的開發方式。 如果你不熟悉這個概念, 你可以稍微google一下這個主題。

CodeIgniter的單元測試類別非常簡單, 由一個評估函數以及兩個結果函數構成。 它並不打算成為一個完整成熟的測試套件, 而只提供了簡單的機制讓你評估你的程式碼, 來決定它是否產生正確的資料型別與結果。

類別初始化

如同在CodeIgniter中其他大多數的類別, 單元測試類別可經由你的控制器(controller)使用$this->load->library函數來初始化:

$this->load->library('unit_test');

一旦載入了, 單元測試物件可經由:$this->unit來使用

執行測試

透過提供給下列函數測試與預期的結果來執行測試:

$this->unit->run( test, expected result, 'test name' );

Where test is the result of the code you wish to test, expected result is the data type you expect, test name is an optional name you can give your test, and notes are optional notes. Example:

$test = 1 + 1;

$expected_result = 2;

$test_name = 'Adds one plus one';

$this->unit->run($test, $expected_result, $test_name);

你提供的預期結果可以是資料型別相符或是文字相符。這是文字相符的範例:

$this->unit->run('Foo', 'Foo');

這是資料型別相符的範例:

$this->unit->run('Foo', 'is_string');

注意到在第二個參數用到"is_string"了嗎?這是要告訴函數評估你的測試結果是否為字串。 這裡有一份可比較型別的清單:

產生報告

你可以在每個測試後顯示測試結果, 或是在數個測試結束後產生一份報告。 要直接顯示一份報告的話, 只要echo或返回run函數:

echo $this->unit->run($test, $expected_result);

用這樣的方式來執行所有測試並產生全部的報告:

echo $this->unit->report();

報告將會格式化成一個HTML表格。如果你偏好原始資料, 你可以用下列方式返回一個陣列:

echo $this->unit->result();

嚴格模式(Strict Mode)

單元測試預設會用較鬆散的方式比較文字是否符合。考慮這個參考範例:

$this->unit->run(1, TRUE);

測試評估的是一個整數(integer), 但是預期結果是一個布林值(boolean)。而由於PHP的型別鬆散特性, 以上的程式如果用一般的相等測試結果會是TRUE:

if (1 == TRUE) echo 'This evaluates as true';

如果你需要, 你可以把單元測試類別置於嚴格模式(strict mode)中, 這樣它將同時檢查值與資料型別:

if (1 === TRUE) echo 'This evaluates as FALSE';

這樣可以啟動嚴格模式(strict mode):

$this->unit->use_strict(TRUE);

啟動/取消單元測試

如果你想要把一些測試留在程式碼中, 但是只想在需要的時候執行, 你可以用以下方法取消單元測試:

$this->unit->active(FALSE)

Unit Test Display

When your unit test results display, the following items show by default:

You can customize which of these items get displayed by using $this->unit->set_items(). For example, if you only wanted the test name and the result displayed:

Customizing displayed tests

$this->unit->set_test_items(array('test_name', 'result'));

建立模板

如果你不想用預設的測試結果格式, 你可以設定自己的模板。 這是一個簡單的模板範例。請注意需要的虛擬變數:

$str = '
<table border="0" cellpadding="4" cellspacing="1">
    {rows}
        <tr>
        <td>{item}</td>
        <td>{result}</td>
        </tr>
    {/rows}
</table>';

$this->unit->set_template($str);

注意:你的模板必須在測試程序執行之前宣告。