一、使用依赖关系
通过在测试函数前添加 @depends 注解,来将需求函数的返回值作为参数获取
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
public function test_push()
{
$stack = [];
array_push($stack,'m');
return $stack;
}
/**
* @depends test_push
*
* 使用一个注解来获取一个测试函数的返回值作为一个参数
*/
public function test_push2($stack)
{
$m = array_pop($stack);
$this->assertEquals($m,'m');
array_push($stack,'y');
return $stack;
}
/**
* @depends test_push
* @depends test_push2
*
* 使用多个注解来获取多个测试函数的返回值作为多个参数
*/
public function test_pop($stack1,$stack2){
$m = array_pop($stack1);
$y = array_pop($stack2);
$this->assertEquals($m,'m');
$this->assertEquals($y,'y');
}
}
?>
二、使用数据供给器
测试方法可以接受任意参数。这些参数由数据供给器方法。用 @dataProvider 标注来指定使用哪个数据供给器方法。
数据供给器方法必须声明为 public,其返回值要么是一个数组,其每个元素也是数组;要么是一个实现了 Iterator 接口的对象,在对它进行迭代时每步产生一个数组。每个数组都是测试数据集的一部分,将以它的内容作为参数来调用测试方法。
<?php
class DataTest extends PHPUnit_Framework_TestCase
{
public function additionProvider()
{
return [
[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 2]
];
}
/**
* @dataProvider additionProvider
*
* 使用数据供给器获取大量数据
* 其返回值必须是二维数组,或者实现了Iterator接口,以此来保证每步产生一个数组
*/
public function test_add($a, $b, $c)
{
$this->assertEquals($c, $a + $b);
}
}
?>
三、使用预期输出
有时候,想要断言(比如说)某方法的运行过程中生成了预期的输出(例如,通过 echo 或 print)。PHPUnit\Framework\TestCase 类使用 PHP 的 输出缓冲 特性来为此提供必要的功能支持。
如果没有产生预期的输出,测试将计为失败。
<?php
class OutputTest extends PHPUnit_Framework_TestCase
{
public function testExpectFooActualFoo()
{
$this->expectOutputString('foo');
print 'foo';
}
public function testExpectBarActualBaz()
{
$this->expectOutputString('bar');
print 'baz';
}
}
?>
方法 | 含义 |
---|---|
void expectOutputRegex(string $regularExpression) | 设置输出预期为输出应当匹配正则表达式 $regularExpression。 |
void expectOutputString(string $expectedString) | 设置输出预期为输出应当与 $expectedString 字符串相等。 |
bool setOutputCallback(callable $callback) | 设置回调函数,用来做诸如将实际输出规范化之类的动作。 |
注意
在严格模式下,本身产生输出的测试将会失败。
四、在控制台输出信息
//输出变量
var_dump($value)
//打印信息
fwrite(STDOUT, __METHOD__ . " hello world\n");
五、使用group进行分组测试
在方法前加上注解@group xx来将测试方法分组
/**
* @group user
*/
public function test_getUserInfo()
{
fwrite(STDOUT, "\n---------------------------\n");
fwrite(STDOUT, __METHOD__ . ":获取我的信息测试用例结果:\n");
}
输入指令列出所有分组:
# phpunit --list-groups FILE_NAME
执行指定分组:
# phpunit --group GROUP_NAME FILE_NAME