aidan-casey / mock-client
符合PSR规范的测试模拟客户端。
dev-master
2024-09-14 01:56 UTC
Requires
- php: ^8.2
- php-http/discovery: ^1.14
- phpunit/phpunit: ^11.3.5
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-factory-implementation: ^1.0
- psr/http-message: ^1.0|^2.0
Requires (Dev)
- guzzlehttp/psr7: ^2.6
This package is not auto-updated.
Last update: 2024-09-14 02:03:14 UTC
README
此测试客户端符合PSR-18规范,允许你在任何可能替换客户端的场景中使用它。使用此客户端,您可以确保您的应用程序发送了预期的请求和模拟响应。
此包受到 HTTPlug 的Mock Client 包和 Laravel 的HTTP客户端的启发。此包试图将它们整合成一个有用的类。
安装
要安装此包,请使用Composer
composer require aidan-casey/mock-client:dev-master
测试请求
要开始使用此客户端进行测试,创建一个新实例并将其传递给任何PSR-18兼容的服务。在发出请求后,直接在类上使用断言方法来测试客户端是否正确发送了所有内容。
例如
use AidanCasey\MockClient\Client; use PHPUnit\Framework\TestCase; class MyTest extends TestCase { public function test_it_makes_requests() { $client = new Client; $service = new MyCoolService($client); $service->makeRequest(); $client->assertRequestsWereMade(); } }
目前可用的断言方法如下
assertUri
assertMethod
assertHeaderEquals
assertBodyIs
assertBodyIsEmpty
assertBodyContains
assertRequestsWereMade
assertNoRequestsWereMade
模拟响应
模拟响应允许您确保您的类正确解析它们。此客户端捆绑的几个辅助工具将使此过程更容易。
响应方法
静态 response
方法帮助构建在特定请求时返回的PSR-7响应。此辅助工具接受三个参数:正文、状态码和头部。
例如
use AidanCasey\MockClient\Client; // This will return a body with the string "Hello, world" Client::response('Hello, world', 200, [ 'test-header' => 'test-value' ]); // This will return the contents of the file path. Client::response(__DIR__ . '/stubs/response.json'); // This will return the array in JSON form. Client::response(['key' => 'value']);
假方法
静态 fake
方法允许您将某些URL映射到特定的响应。传入一个数组,您的URL作为键,您的PSR-7响应作为值。
例如
use AidanCasey\MockClient\Client; Client::fake([ 'https://github.com' => Client::response('Hello!'), ]); // You may also use wildcards at any point in the URL. Client::fake([ 'https://github.com/aidan-casey/*' => Client::response('Hello Aidan'), 'https://github.com/*/mock-client' => Client::response('Hello, Stranger'), ]);
多个响应
静态 sequence
和 random
方法允许您按顺序或随机顺序传递一系列响应。如果您想测试您服务的弹性,这些方法可能很有帮助!
例如
use AidanCasey\MockClient\Client; Client::fake([ 'https://github.com/*' => Client::sequence([ Client::response(null, 301), Client::response(null, 201), Client::response(null, 404), ]), 'https://bing.com' => Client::random([ Client::response(null, 401), Client::response(null, 403), Client::response(null, 404), ]) ]);