这篇文章给大家分享的是有关php单元测试如何实现的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。
windows开发环境下,PHP使用单元测试可以使用PHPUnit。
推荐阅读:php服务器
安装PHPUnit
使用 composer 方式安装 PHPUnit,其他安装方式请看这里
composer require --dev phpunit/phpunit ^6.2
安装 Monolog 日志包,做 phpunit 测试记录日志用。
composer require monolog/monolog
安装好之后,我们可以看coomposer.json 文件已经有这两个扩展包了:
"require": {
"monolog/monolog": "^1.23",
},
"require-dev": {
"phpunit/phpunit": "^6.2"
},
PHPUnit简单用法
1、单个文件测试
创建目录tests,新建文件 StackTest.php,编辑如下:
<?php
/**
* 1、composer 安装Monolog日志扩展,安装phpunit单元测试扩展包
* 2、引入autoload.php文件
* 3、测试案例
*
*
*/
namespace App\tests;
require_once __DIR__ . '/../vendor/autoload.php';
define("ROOT_PATH", dirname(__DIR__) . "/");
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase
{
public function testPushAndPop()
{
$stack = [];
$this->assertEquals(0, count($stack));
array_push($stack, 'foo');
// 添加日志文件,如果没有安装monolog,则有关monolog的代码都可以注释掉
$this->Log()->error('hello', $stack);
$this->assertEquals('foo', $stack[count($stack)-1]);
$this->assertEquals(1, count($stack));
$this->assertEquals('foo', array_pop($stack));
$this->assertEquals(0, count($stack));
}
public function Log()
{
// create a log channel
$log = new Logger('Tester');
$log->pushHandler(new StreamHandler(ROOT_PATH . 'storage/logs/app.log', Logger::WARNING));
$log->error("Error");
return $log;
}
}
代码解释:
StackTest为测试类
StackTest 继承于 PHPUnit\Framework\TestCase
测试方法testPushAndPop(),测试方法必须为public权限,一般以test开头,或者你也可以选择给其加注释@test来表
在测试方法内,类似于 assertEquals() 这样的断言方法用来对实际值与预期值的匹配做出断言。
命令行执行:
phpunit 命令 测试文件命名
framework# ./vendor/bin/phpunit tests/StackTest.php
// 或者可以省略文件后缀名
// ./vendor/bin/phpunit tests/StackTest
执行结果:
➜ framework# ./vendor/bin/phpunit tests/StackTest.php
PHPUnit 6.4.1 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 56 ms, Memory: 4.00MB
OK (1 test, 5 assertions)
感谢各位的阅读!关于php单元测试如何实现就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。