alekseytupichenkov/guzzle_stub

此仓库提供了具有灵活设置的 Guzzle stub

安装数: 11,897

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 0

公开问题: 0

类型:guzzle-extension

2.0.0 2021-08-12 15:24 UTC

This package is auto-updated.

Last update: 2024-09-12 22:26:16 UTC


README

Build Status Coverage Status Scrutinizer Code Quality License

目录

介绍

此仓库提供了具有灵活设置的 Guzzle stub。

安装

  1. 下载

    在控制台中运行命令

    $ composer require --dev alekseytupichenkov/guzzle_stub

基本用法

如果您有一个 Guzzle 客户端,需要编写 stub 并排除向外部服务发送请求的可能性

例如

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

class MySuperGuzzleClient extends Client
{
    public function __construct(HandlerStack $handlerStack = null)
    {
        parent::__construct([
            'timeout' => 300,
            'base_uri' => 'http://foo.bar',
            'handler' => $handlerStack ?? HandlerStack::create(),
        ]);
    }
}

使用现有的 Guzzle 客户端创建 Guzzle 客户端 stub 类,添加 trait GuzzleClientTrait,实现 loadFixtures 方法并将其添加到其中

use Alekseytupichenkov\GuzzleStub\Model\Fixture;
use Alekseytupichenkov\GuzzleStub\Traits\GuzzleClientTrait;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

class MySuperGuzzleClientStub extends MySuperGuzzleClient
{
    use GuzzleClientTrait;

    function loadFixtures()
    {
        $this->append(new Fixture(
            new Request('GET', 'http://foo.bar/baz', ['token' => '.*']),
            new Response(200, [], '{"result":"ok"}')
        ));

        $this->append(new Fixture(
            new Request('POST', 'http://foo.bar/baz', ['token' => '.*'], '{"data":".*"}'),
            new Response(200, [], '{"result":"ok"}')
        ));
    }
}

现在您可以编写测试来检查请求/响应的历史记录

use PHPUnit\Framework\TestCase;

class MySuperGuzzleClientStubTest extends TestCase
{
    /** @var MySuperGuzzleClientStub */
    private $client;

    public function setUp()
    {
        $this->client = new MySuperGuzzleClientStub();
    }

    public function testPost()
    {
        $response = $this->client->post('/baz', [
            'headers' => [
                'token' => '123'
            ],
            'body' => '{"data":"test"}'
        ]);

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('{"result":"ok"}', $response->getBody()->__toString());
        $this->assertEquals(1, $this->client->getHistoryCount());
        $this->assertEquals($response, $this->client->getLatestHistoryResponse());
    }
}

如果 stub 没有合适的 fixture,您将得到如下异常

1) MySuperGuzzleClientStubTest::testException
Alekseytupichenkov\GuzzleStub\Exception\GuzzleStubException: Can't find suitable response for request [array (
  'method' => 'POST',
  'uri' => '/without/fixture',
  'body' => '',
  'protocol_version' => '1.1',
  'headers' =>
  array (
    'User-Agent' =>
    array (
      0 => 'GuzzleHttp/6.3.3 curl/7.54.0 PHP/7.1.18',
    ),
    'Host' =>
    array (
      0 => 'foo.bar',
    ),
  ),
)]