ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## http测试 这篇主要讲 `http测试`,参考了[laravel-# HTTP 测试](https://learnku.com/docs/laravel/7.x/http-tests/7506) [phpunit文档](http://www.phpunit.cn/manual/7.0/zh_cn/installation.html) ## 安装phpunit 可以通过 `PHAR` 方式,也可以通过 `composer`。 用 `composer` 吧,更方便。 ``` composer require phpunit/phpunit ``` 安装成功后, 将会有 `vendor/bin/phpunit` 文件。 ![](https://img.kancloud.cn/9b/8f/9b8f7887bdc9d5c69e3b25885e6e8c30_598x108.png) ## 创建phpunit.xml `phpunit` 的配置文件,当你运行`phpunit`的时候, 自动在你这个目录找配置文件。 一次性测试多个文件,是靠 `phpunit.xml` 来配置的。 ``` <?xml version="1.0" encoding="UTF-8"?> <!-- 版本 编码 声明--> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/schema/9.3.xsd" bootstrap="vendor/autoload.php" colors="true" > <!-- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" --> <!-- xsi:noNamespaceSchemaLocation: 不用命名空间加载xsd文件 更详细我也不懂, 详细见: https://www.runoob.com/schema/schema-tutorial.html --> <!-- bootstrap: 测试之前加载的文件 --> <!-- color: 启用颜色 --> <testsuites> <testsuite name="php_frame"> <!-- name套件名称 就是"组" 可以有多个套件 --> <!-- 声明tests文件夹 后缀是Test.php是测试文件 --> <directory suffix="Test.php">./tests</directory> </testsuite> </testsuites> </phpunit> ``` ## 创建core/TestCase.php 封装 `phpunit`。 ``` <?php namespace core; use core\request\PhpRequest; use PHPUnit\Framework\TestCase as BaseTestCase; class TestCase extends BaseTestCase { protected $response; // 路由请求响应的结果 // 基境共享 protected function setUp(): void { require_once __DIR__ . '/../app.php'; } // 调用路由 public function call($uri,$method) { \App::getContainer()->bind(\core\request\RequestInterface::class,function () use ($uri,$method){ // 将request绑定到容器 return PhpRequest::create($uri,$method); }); return $this->response = app('response')->setContent( // 响应 app('route')->dispatch( // 路由 \App::getContainer()->get(\core\request\RequestInterface::class) // 调用绑定request ) ); } // get方式调用 public function get($uri,$params = []) { $this->call($uri,'GET',$params); return $this; } // post方式调用 public function post($uri,$params = []) { $this->call($uri,'POST',$params); return $this; } // 断言状态码是否一样 protected function assertStatusCode($status) { $this->assertEquals($status, $this->response->getStatusCode()); return $this; } // ... 其他断言不写了 参考的断言状态码 // 代理模式 访问response public function __call($name, $arguments) { return $this->response->{$name}(... $arguments); } } ``` 至此已经完成了。 ## 运行 ### 创建测试文件 tests/ExampleTest ``` <?php class ExampleTest extends \core\TestCase { // 测试config public function testDatabaseDefault() { // 断言内容是 "mysql_one" $this->assertEquals('mysql_one', config('database.default') ); } // 测试路由 public function testGetRoute() { $this->get('/hello') ->assertStatusCode(200); // 断言状态码是200 } // 测试路由 public function testPostRoute() { $res = $this->get('/hello'); // 断言返回的内容是 "你在访问hello" $this->assertEquals('你在访问hello', $res->getContent()); } } ``` ## 运行测试 ``` vendor\bin\phpunit ``` ![](https://img.kancloud.cn/8e/0c/8e0cf7cb7f72468a9811e065b3fe9561_1002x936.png)