好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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单元测试怎么写的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于php单元测试怎么写的详细内容...

  阅读:37次