PHP code example of alekseytupichenkov / guzzle_stub

1. Go to this page and download the library: Download alekseytupichenkov/guzzle_stub library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alekseytupichenkov / guzzle_stub example snippets


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(),
        ]);
    }
}

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());
    }
}

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',
    ),
  ),
)]