data_pipelines-1.x-dev/tests/src/Traits/MockHttpClientTrait.php

tests/src/Traits/MockHttpClientTrait.php
<?php

declare(strict_types=1);

namespace Drupal\Tests\data_pipelines\Traits;

use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;

/**
 * Defines a trait for mocking the http client.
 */
trait MockHttpClientTrait {

  /**
   * History of requests/responses.
   *
   * @var array
   */
  protected $history = [];

  /**
   * Mock client.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $mockClient;

  /**
   * Mock handler.
   *
   * @var \GuzzleHttp\Handler\MockHandler
   */
  protected $mockHandler;

  /**
   * Mocks the http-client.
   */
  protected function mockClient() {
    if (!isset($this->mockClient)) {
      // Create a mock and queue responses.
      $this->mockHandler = new MockHandler();

      $handler_stack = HandlerStack::create($this->mockHandler);
      $history = Middleware::history($this->history);
      $handler_stack->push($history);
      $this->mockClient = new Client(['handler' => $handler_stack]);
    }
    $this->container->set('http_client', $this->mockClient);
  }

  /**
   * Mocks responses.
   *
   * @param array $responses
   *   Array of responses, callables, or exceptions.
   */
  protected function mockResponses(array $responses): void {
    foreach ($responses as $response) {
      $this->mockHandler->append($response);
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc