'GuzzlePHP mock response content

I want to mock a response to the Guzzle request:

 $response = new Response(200, ['X-Foo' => 'Bar']);

 //how do I set content of $response to--> "some mocked content"

 $client = Mockery::mock('GuzzleHttp\Client');
 $client->shouldReceive('get')->once()->andReturn($response);

I noticed I need to add as third parameter the interface:

 GuzzleHttp\Stream\StreamInterface

but there are so many implementations of it, and I want to return a simple string. Any ideas?

Edit: now I use this:

 $response = new Response(200, [], GuzzleHttp\Stream\Stream::factory('bad xml here'));

but when I check this:

$response->getBody()->getContents()

I get an empty string. Why is this?

Edit 2: this happened to me only when I used xdebug, when it runs normally it works great!



Solution 1:[1]

We'll just keep doing this. The previous answer is for Guzzle 5, this is for Guzzle 6:

use GuzzleHttp\Psr7;

$stream = Psr7\stream_for('{"data" : "test"}');
$response = new Response(200, ['Content-Type' => 'application/json'], $stream);

Solution 2:[2]

Using @tomvo answer and the comment from @Tim - this is what I did for testing Guzzle 6 inside my Laravel app:

use GuzzleHttp\Psr7\Response;

$string = json_encode(['data' => 'test']);
$response = new Response(200, ['Content-Type' => 'application/json'], $string);

$guzzle = Mockery::mock(GuzzleHttp\Client::class);
$guzzle->shouldReceive('get')->once()->andReturn($response);

Solution 3:[3]

Guzzle\Http\Message\Response allows you to specify the third parameter as a string.

$body = '<html><body>Hello world!</body></html>';
$response = new Response(200, ['X-Foo' => 'Bar'], $body);

If you'd prefer a solution that implements Guzzle\Stream\StreamInterface, then I recommend using Guzzle\Http\EntityBody for the most straightforward implementation:

$body = Guzzle\Http\EntityBody::fromString('<html><body>Hello world!</body></html>');
$response = new Response(200, ['X-Foo' => 'Bar'], $body);

Solution 4:[4]

For Guzzle 7, you can use the GuzzleHttp\Psr7\Utils::streamFor() method as follows:

$data = json_encode(['X-Foo' => 'Bar']);
$stream = Utils::streamFor($data);

And then you can pass the $stream object to the andReturn method of the mocked client.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tomvo
Solution 2 Laurence
Solution 3 Jacob Budin
Solution 4 M074554N