您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
phpunit测试的依赖关系(depends)及assertEmpty,assertSame,assertNotEmpty的使用
发布时间:2021-09-12 17:35:55编辑:雪饮阅读()
- 生产者(producer),是能生成被测单元并将其作为返回值的测试方法。
- 消费者(consumer),是依赖于一个或多个生产者及其返回值的测试方法。
有时候一个测试方法可能会依赖另外一个测试方法,另外一个测试又会再依赖其它方法。
一个测试实例如:StackTest.php
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class StackTest extends TestCase
{
public function testEmpty(): array
{
$stack = [];
//原型:assertEmpty(mixed $actual[, string $message = ''])
//当 $actual 非空时报告错误,错误讯息由 $message 指定。
$this->assertEmpty($stack);
return $stack;
}
/**
* @depends testEmpty
*/
public function testPush(array $stack): array
{
array_push($stack, 'foo');
//原型:assertSame(mixed $expected, mixed $actual[, string $message = ''])
//当两个变量 $expected 和 $actual 的值与类型不完全相同时报告错误,错误讯息由 $message 指定。
$this->assertSame('foo', $stack[count($stack)-1]);
//assertNotEmpty() 是与assertEmpty相反的断言,接受相同的参数。
$this->assertNotEmpty($stack);
return $stack;
}
/**
* @depends testPush
*/
public function testPop(array $stack): void
{
//array_pop() 函数删除数组中的最后一个元素。并返回最后一个元素
$this->assertSame('foo', array_pop($stack));
$this->assertEmpty($stack);
}
}
use PHPUnit\Framework\TestCase;
final class StackTest extends TestCase
{
public function testEmpty(): array
{
$stack = [];
//原型:assertEmpty(mixed $actual[, string $message = ''])
//当 $actual 非空时报告错误,错误讯息由 $message 指定。
$this->assertEmpty($stack);
return $stack;
}
/**
* @depends testEmpty
*/
public function testPush(array $stack): array
{
array_push($stack, 'foo');
//原型:assertSame(mixed $expected, mixed $actual[, string $message = ''])
//当两个变量 $expected 和 $actual 的值与类型不完全相同时报告错误,错误讯息由 $message 指定。
$this->assertSame('foo', $stack[count($stack)-1]);
//assertNotEmpty() 是与assertEmpty相反的断言,接受相同的参数。
$this->assertNotEmpty($stack);
return $stack;
}
/**
* @depends testPush
*/
public function testPop(array $stack): void
{
//array_pop() 函数删除数组中的最后一个元素。并返回最后一个元素
$this->assertSame('foo', array_pop($stack));
$this->assertEmpty($stack);
}
}
这里面testPop方法是想要从数组中删除一个元素,那么你就得需要一个非空的数组,需要它依赖于testPush方法,而testPush方法要想push则一般的肯定最好是有一个空数组供测试,所以它又依赖testEmpty这个方法。
那么在测试中依赖另外一个方法使用depends关键字进行注解。
那么接下来我们可以试试运行下上面实例中3个方法中的所有断言方法测试了。
C:\Users\Administrator>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe D:\phpstudy_pro\Extensions\php\php7.3.4nts\phpunit-9.5.8.phar C:\Users\Administrator\PhpstormProjects\untitled\StackTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
... 3 / 3 (100%)
Time: 00:00.005, Memory: 20.00 MB
OK (3 tests, 5 assertions)
那么以上实例就引出一个新的概念,生产者与消费者。
关键字词:phpunit,depends,assertEmpty,assertSame,assertNotEmpty