您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php单元测试怎么写

2024/3/24 2:07:48发布34次查看
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.phpphpunit 6.4.1 by sebastian bergmann and contributors. .                                                                   1 / 1 (100%)time: 56 ms, memory: 4.00mbok (1 test, 5 assertions)
以上就是php单元测试怎么写的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product