CodeIgniter 用户指南 版本 2.0.0

PHP100中文网
查看原文

单元测试类

单元测试是一种用于测试应用程序中每个函数的软件开发方法。如果你对此概念不熟悉,或许需要google一下相关概念。

CodeIgniter的单元测试类非常简单,由一个评估函数和两个结果函数组成。它没打算成为一个十全的测试集,只提供一个简单的能够评测你的代码是否可以产生正确的数据类型及结果的解决方案。

初始化单元类

和大多数其它的类一样,在CodeIgniter中,单元测试类一样要在控制器中用函数$this->load->library 来初始化:

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

测试类一旦加载,单元测试对象可以这样使用:$this->unit

运行测试:

运行一个测试应提供一个测试及期望的结果给以下函数:

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

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);

你所给出的期望结果($expected_result)可以是字面上匹配(literal match)的也可以是数据类型上匹配的。下例为字面匹配(literal match):

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

下例为类型匹配(data type match):

$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();

严格模式

默认情况下,单元测试类评测字面匹配(literal match)时比较宽松,考虑以下例子:

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

此测试评测的是一个整数,但是期望结果却是布尔值。不过,由于PHP是弱类型语言,使用正常的相等测试,以上代码返回的将是TRUE:

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

喜欢的话,你可以让单元测试类在严格模式下执行,这样它会同时比较两数据的类型及值:

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

启用严格模式:

$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'));

Creating a Template

如果你希望测试结果以自定义的格式显示,这里提供一个简单的模板示例。注意必需的伪变量(seudo-variables):

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

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

注意: 你的模板必须在单元测试运行之前声明。

 

翻译贡献者: Hex, iptton
最后修改: 2011-02-01 02:08:18