您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
如何对php进行单元测试 单元测试编写
发布时间:2021-08-12 12:12:49编辑:雪饮阅读()
单元测试首先需要安装配置phpunit:https://www.gaojiupan.cn/manshenghuo/chengxurensheng/3833.html
然后是如何编写一个简单的单元测试,php中单元测试,需要编写一个单元测试类,这个自定义的单元测试类必须继承PHPUnit\Framework\TestCase类
这个自定义的测试类中每个测试方法名称都必须以test开头。
那么这里假定我编写一个自定义的测试类StackTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class StackTest extends TestCase
{
public function testPushAndPop(): void
{
$stack = [];
$this->assertSame(0, count($stack));
array_push($stack, 'foo');
$this->assertSame('foo', $stack[count($stack)-1]);
$this->assertSame(1, count($stack));
$this->assertSame('fool', array_pop($stack));
$this->assertSame(0, count($stack));
}
}
该测试类中仅写了一个测试方法,该方法里面写了5个断言。很明显的倒数第二个断言在数组出栈的时候返回的值应该是foo而不是fool,所以这里断言与结果实际上是不一致的。
那么如何运行这个测试类呢?
运行一个单元测试,我们只需要用phpunit去执行这个如StackTest.php脚本即可。
如:
这里可以看到,已经按预期的在fool这里的断言给报错了。
这里的运行结果中其中在运行测试方法时断言失败时打印“F”,而在运行测试成功时打印”.”
所以刚才的fool处的断言我们修改为foo如:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class StackTest extends TestCase
{
public function testPushAndPop(): void
{
$stack = [];
$this->assertSame(0, count($stack));
array_push($stack, 'foo');
$this->assertSame('foo', $stack[count($stack)-1]);
$this->assertSame(1, count($stack));
$this->assertSame('foo', array_pop($stack));
$this->assertSame(0, count($stack));
}
}
那么当我们再次执行单元测试时候就会出现单元测试通过的打印。
D:\phpstudy_pro\Extensions\php\php7.3.4nts>php phpunit-9.5.8.phar StackTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.003, Memory: 20.00 MB
OK (1 test, 5 assertions)
参考资料:https://phpunit.readthedocs.io/en/9.5/writing-tests-for-phpunit.html
参考资料:https://phpunit.readthedocs.io/en/9.5/textui.html
关键字词:php,单元测试,单元测试编写