jcchavezs / httptest
0.2.1
2018-05-31 15:51 UTC
Requires
- ext-pcntl: *
- react/http: 0.8.*
Requires (Dev)
- php: >=5.4||^7.0
- phpunit/phpunit: ^4.8.36
- squizlabs/php_codesniffer: ^3.0@dev
This package is auto-updated.
Last update: 2024-09-04 20:27:30 UTC
README
HTTP集成测试库。
HttpTest 强烈受到 httptest go 库 的启发
描述
在测试包含HTTP调用的函数时,开发者通常会在cURL函数周围创建一个包装类,并模拟该类以进行单元测试。这种技术可以测试类,但测试实际的HTTP调用也很重要,这需要有一个监听这些调用的HTTP服务器。这个库提供了一个这样的服务器,并允许开发者在客户端和服务器端进行断言。
安装
composer require --dev jcchavezs/httptest
使用
测试cURL HTTP请求
<?php namespace HttpTest\Tests\Integration; use HttpTest\HttpTestServer; use PHPUnit_Framework_TestCase; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; final class TestServerTest extends PHPUnit_Framework_TestCase { const TEST_BODY = 'test_body'; const TEST_STATUS_CODE = 202; public function testHttpSuccess() { $t = $this; $server = HttpTestServer::create( function (RequestInterface $request, ResponseInterface &$response) use ($t) { /* Assert the HTTP call includes the expected values */ $t->assertEquals('POST', $request->getMethod()); $t->assertEquals('application/json', $request->getHeader('Content-Type')[0]); $t->assertEquals(self::TEST_BODY, (string) $request->getBody()); $response = $response->withStatus(self::TEST_STATUS_CODE); } ); $server->start(); $handle = curl_init($server->getUrl()); curl_setopt($handle, CURLOPT_POST, 1); curl_setopt($handle, CURLOPT_POSTFIELDS, self::TEST_BODY); curl_setopt($handle, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen(self::TEST_BODY), ]); if (curl_exec($handle) === true) { $statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); curl_close($handle); // Assert client behaviour based on the server response $this->assertEquals(self::TEST_STATUS_CODE, $statusCode); } else { // Stop the server before as `$this->fail(...)` throws an exception // In a try/catch block, this should be in the finally block $server->stop(); $this->fail(curl_error($handle)); } $server->stop(); } }
重要: httptest-php
使用 pcntl_fork
在单独的线程中运行服务器。在编写测试时要考虑这一点,更重要的是,在完成调用后立即停止服务器,因为对象是从父进程复制到子进程的,这可能导致断言的实际值在计数外部资源调用(例如,将日志条目写入文件)时乘以2。
测试
composer test