elnoro / php-http-mock
使用本地PHP服务器模拟外部API的简单解决方案(无二进制依赖项)
dev-main
2022-10-08 14:41 UTC
Requires
- symfony/http-foundation: ^6.0
- symfony/process: ^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.6
- phpunit/phpunit: ^9.5
- symfony/http-client: ^6.0
- vimeo/psalm: ^4.21
This package is not auto-updated.
Last update: 2024-10-03 11:04:00 UTC
README
使用本地PHP服务器模拟外部API的简单解决方案(无二进制依赖项)
专为PHPUnit设计,但您可以将其用于任何东西。
工作原理
每次调用ApiMocker::start时,都会启动一个新的本地PHP服务器(通过php -S)。
服务器从临时文件中读取其路由配置(URL、方法和相应的响应)。此文件在每次请求时都会重新读取,因此您可以在服务器启动后重新配置路由和响应。
此文件由php-http-mock软件包自动写入和创建,并通过环境变量传递给服务器。
示例
<?php declare(strict_types=1); namespace Test\Integration\App\HttpMock\Client; use App\HttpMock\Client\ApiMocker; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpClient\HttpClient; use Symfony\Contracts\HttpClient\HttpClientInterface; final class ApiMockerTest extends TestCase { private ApiMocker $apiMocker; private HttpClientInterface $httpClient; protected function setUp(): void { $this->apiMocker = ApiMocker::create(); $this->apiMocker->start(); $this->httpClient = HttpClient::createForBaseUri($this->apiMocker->getBaseUri()); } protected function tearDown(): void { $this->apiMocker->stop(); } /** * @test */ public function allowsDifferentResponsesOnTheSameUri(): void { $this->apiMocker->routeWillReturn('/expected-uri', responseCode: 400, responseBody: 'get response'); $this->apiMocker->routeWillReturn('/expected-uri', 'POST', 500, 'post response'); $getResponse = $this->httpClient->request('GET', '/expected-uri'); $this->assertSame(400, $getResponse->getStatusCode()); $this->assertSame('get response', $getResponse->getContent(false)); $postResponse = $this->httpClient->request('POST', '/expected-uri'); $this->assertSame(500, $postResponse->getStatusCode()); $this->assertSame('post response', $postResponse->getContent(false)); } /** * @test */ public function returnsRequestsMadeToApiServer(): void { $this->apiMocker->routeWillReturn('/request?to=keep', 'POST'); $this->httpClient->request('POST', '/request?to=keep', ['body' => 'expected-body']); $request = $this->apiMocker->lastRequestOn('/request?to=keep', 'POST'); $this->assertSame('expected-body', $request->getContent()); } }
开发命令
composer test
- 自解释
composer cov
- 生成覆盖率html & xml
coverage ci
- 运行php-cs-fixer、psalm和测试
coverage fixcs
- 自动修复代码风格