进行单元测试我是用phpunit和GuzzleHttp。
一、安装phpunit
composer require phpunit/phpunit
二、安装GuzzleHttp
composer require guzzlehttp/guzzle
三、修改composer.json文件
{
"require": {
"phpunit/phpunit": "^8.5",
"guzzlehttp/guzzle": "~6.0"
},
"autoload": {
"psr-4": {
"app\\": "application/",
"basic\\": "extend/basic",
"traits\\": "extend/traits",
"tests\\": "tests/"
}
}
}
修改完后,更新下composer
composer dumpautoload
四、添加或修改phpunit.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="tests/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Application Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">application/</directory>
</whitelist>
</filter>
<php>
<server name='HTTP_ACCEPT' value='*' />
</php>
</phpunit>
bootstrap参数栏,是用来加载tp机制的。
五、设置加载TP机制,也就是bootstrap参数栏的tests目录下的autoload.php
<?php
use think\Config;
use think\Db;
// 初始化app
define('APP_PATH', dirname(__DIR__) . '/application/');
define('VENDOR_PATH', APP_PATH . 'vendor' . DIRECTORY_SEPARATOR); // 让tp不用自己的载入机制,而使用composer的autoload
require_once dirname(__DIR__) . '/vendor/autoload.php';
include dirname(__DIR__) . '/core/base.php';
include dirname(__DIR__) . '/core/helper.php';
Config::load(APP_PATH . '/database.php', 'database');
相当于进行单元测试的入口。
六、开始单元测试编写啦,也就是在tests目录创建个XxApiTest.php
<?php
namespace tests;
use PHPUnit\Framework\TestCase;
use GuzzleHttp\Client;
class XxApiTest extends TestCase
{
public $client;
public function __construct(?string $name = null, array $data = [], string $dataName = '')
{
parent::__construct($name, $data, $dataName);
$this->client = new Client([
'base_uri' => 'https://www.baidu.com/',
'verify' => false,
'headers' => [
'Accept' => '*',
]
]);
}
public function testXxApi() {
$resp = $this->client->request('POST', 'XxApi', [
'form_params' => [
'token' => '123456'
],
]);
$this->assertEquals(200, $resp->getStatusCode());
}
}
七、相关单元测试写完后,在根目录下执行phpunit命令就行了
//测试所有
phpunit