Unit Testing Mock Guzzle Response I'm trying to test a method that makes an HTTP request via Guzzle, so I can see if my code that filters that response is working. I have a mock json response in a json file that I want to use to test it. This is simply a saved version of an actual response. 

I know you can mock methods e.g. this would override the get method to return a mock Guzzle Response. How do you mock a Guzzle response in Drupal 8?

    $this-&gt;mockHttp-&gt;expects($this-&gt;any())
      -&gt;method('get')
      -&gt;willReturn($mockGuzzleResponseShouldGoHere);


The mock Guzzle response needs to have a mock method getBody so I can do something like this: 

$this-&gt;mockHttp-&gt;expects($this-&gt;any())
      -&gt;method('getBody')
      -&gt;willReturn(__DIR__ . 'Mocks/membership-classes.json');


and make sure that getBody returns my mock json file.

Method to test that makes a Http Guzzle request

&lt;?php 

/**
   * Call the GetMembershipClasses service.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   */
  public function getMembershipClasses() {

    try {
      // Load configuration for this module.
      $response = $this-&gt;http_client-&gt;get(
        $this-&gt;getBaseUrl() . '/2014/06/membershipClasses', [
          'headers' =&gt; $this-&gt;getAnonymousHeaders(),
        ]);

        $response = json_decode($response-&gt;getBody());

        // Get to the meat of the response.
        $response = $response-&gt;GetMembershipClassesResponseMessage-&gt;MembershipClasses-&gt;MembershipClass;

        // Validate returned data.
        $filtered = array();
        foreach ($response as $membership_class) {
          $membership_class-&gt;MembershipClassCode = $this-&gt;removeSpaces($membership_class-&gt;MembershipClassCode);
          if ($membership_class-&gt;IsActive === TRUE) {
            $filtered[] = $membership_class;
          }
        }
        return new JsonResponse($filtered);
    }
    catch (RequestException $e) {
      return $this-&gt;handleError($e);
    }

  }


And the test class

&lt;?php

/**
 * Class RouteControllerAnonymousTest.
 *
 */
class AnonymousWebServicesTest extends UnitTestCase {

  /**
   * Mock of http_client service.
   *
   * @var \GuzzleHttp\Client
   */
  protected $mockHttp;

  /**
   * Mock of state service.
   *
   * @var \Drupal\Core\State\State
   */
  protected $mockState;

  /**
   * Mock of config.factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $mockConfigFactory;

  /**
   * Set up method which is called before any tests are
   * run. Mocks of the services that the class being tested rely on are
   * created.
   *
   * @return void
   */
  protected function setUp() {

    parent::setUp();
    $mockHttp = $this
      -&gt;getMockBuilder('GuzzleHttp\Client')
      -&gt;disableOriginalConstructor()
      -&gt;setMethods(['get', 'getBody'])
      -&gt;getMock();
    $this-&gt;mockHttp = $mockHttp;

    $mockState = $this
      -&gt;getMockBuilder('Drupal\Core\State\State')
      -&gt;disableOriginalConstructor()
      -&gt;getMock();
    $this-&gt;mockState = $mockState;

    $mockConfigFactory = $this
      -&gt;getMockBuilder('\Drupal\Core\Config\ConfigFactory')
      -&gt;disableOriginalConstructor()
      -&gt;getMock();
    $this-&gt;mockConfigFactory = $mockConfigFactory;

  }

  /**
   * Test the getMembershipClasses method.
   */
  public function testGetMembershipClasses() {

    // This needs to mock a Guzzle response from a get request
    $this-&gt;mockHttp-&gt;expects($this-&gt;any())
      -&gt;method('get')
      -&gt;willReturn('The mock guzzle response should go here);

    $this-&gt;mockHttp-&gt;expects($this-&gt;any())
      -&gt;method('getBody')
      -&gt;willReturn(__DIR__ . 'Mocks/membership-classes.json');

    $anonymousWebServices = new AnonymousWebServices(
      $this-&gt;mockHttp,
      $this-&gt;mockState,
      $this-&gt;mockConfigFactory
    );

    $membership_classes = $anonymousWebServices-&gt;getMembershipClasses();
    var_dump($membership_classes);
    // Insert some assert statement here

  }

}
Guzzle includes a mock handler that lets you provide a mock HTTP response. Docs are at http://docs.guzzlephp.org/en/latest/testing.html. Here's how you might use it in your unit test:

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

/**
 * Test the getMembershipClasses method.
 */
public function testGetMembershipClasses() {

  $body = file_get_contents(__DIR__ . '/Mocks/membership-class.json');
  // This sets up the mock client to respond to the first request it gets
  // with an HTTP 200 containing your mock json body.
  $mock = new MockHandler([
    new Response(200, [], $body),
  ]);
  $handler = HandlerStack::create($mock);
  $this-&gt;mockHttp = new HttpClient(['handler' =&gt; $handler]);

  $anonymousWebServices = new AnonymousWebServices(
    $this-&gt;mockHttp,
    $this-&gt;mockState,
    $this-&gt;mockConfigFactory
  );

  $membership_classes = $anonymousWebServices-&gt;getMembershipClasses();
  $membership_classes = json_decode($membership_classes-&gt;getContent());

  $this-&gt;assertNotEmpty($membership_classes);
  foreach ($membership_classes as $membership_class) {
    $this-&gt;assertTrue($membership_class-&gt;IsActive === TRUE);

  }

}


You can queue multiple mock responses by adding them to your handler at creation time:

  $mock = new MockHandler([
    new Response(200, [], $body),
    new Response(400, [], 'Request malformed.'),
  ]);


Or you can add them after your client has already been instantiated, as long as you keep a reference to your mock handler around. If you have multiple test methods, this is a lot easier to read and maintain:

public function setUp() {
  $this-&gt;mockHandler = new MockHandler();
  $handler = HandlerStack::create($this-&gt;mockHandler);
  $this-&gt;mockHttp = new HttpClient(['handler' =&gt; $handler]);
}

public function testSomething() {
  $this-&gt;mockHandler-&gt;append(new Response(200, [], 'apples and bananas'));
  $responseBody = $this-&gt;mockHttp-&gt;get('http://example.com')-&gt;getBody();
  $this-&gt;assertEquals($responseBody, 'apples and bananas');
}