使用效果
先看下使用效果,我这里是直接在PhpStorm中集成使用的。
由上图测试结果可以看出
StackTest、Stack2Test、Stack3Test单元测试正常
Stack4Test测试有错误,并且标明了错误的具体位置。
我们还可以看到性能 :Time: 00:00.031, Memory: 6.00 MB
前言
PHPUnit是一款轻量级的PHP测试框架。
我们可以通过它来测试脚本、服务、通过断言的方式来校验服务的稳定性
我们还可以测试脚本、服务的性能
PHPUnit手册:点击跳转
安装
PHPUnit的安装方式有很多,但其他方式都可以不用看,看我这个就可以了。其他的真的很麻烦,使用也不方便。
使用composer方式安装:(不了解composer的先去百度了解下)
composer require phpunit/phpunit ^9
集成PhpStorm
PHPUnit的使用方式有多种,但是看我这种集成到PhpStorm一键使用就好了,其他的手动方式太麻烦了,不用看了。
1.配置php版本
点击File | Settings | Languages & Frameworks | PHP,配置PHPlevel和CLI,需要7.2版本
2.配置PHPUnit
点击File | Settings | Languages & Frameworks | PHP | Test Frameworks,选择Use Composer autoloader 配置好对应autoload.php路径,点击右边蓝色的刷新键。
点击Apply,确认配置
3.配置运行脚本
点击Run | Edit Configuration
配置运行脚本名称、测试类的文件夹路径。
4.编写测试类
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase
{
/** @var
* 栈测试数据
*/
protected $stack;
/**
* @var \Api\ApiServer
* 测试服务类
*/
protected $apiServer;
/**
* 测试数组进出
*/
public function testPushAndPop()
{
$stack = [];
$this->assertEquals(0, count($stack));
array_push($stack, 'foo');
$this->assertEquals('foo', $stack[count($stack)-1]);
$this->assertEquals(1, count($stack));
$this->assertEquals('foo', array_pop($stack));
$this->assertEquals(0, count($stack));
}
/**
* 测试用例初始化
*/
protected function setUp(): void
{
$this->stack = [];
$this->apiServer = new \Api\ApiServer();
$this->apiServer->initUserId(1);
}
/**
* api服务测试
*/
public function testApiServer()
{
$data = $this->apiServer->getData();
$this->assertArrayHasKey('ack', $data);
$this->assertArrayHasKey('data', $data);
}
/**
* 空数组测试
*/
public function testEmpty()
{
$this->assertTrue(empty($this->stack));
}
/**
* 数组push测试
*/
public function testPush()
{
array_push($this->stack, 'foo');
$this->assertEquals('foo', $this->stack[count($this->stack)-1]);
$this->assertFalse(empty($this->stack));
}
/**
* 数组pop测试
*/
public function testPop()
{
array_push($this->stack, 'foo');
$this->assertEquals('foo', array_pop($this->stack));
$this->assertTrue(empty($this->stack));
}
}
5.运行脚本
大功告成!