Tzook Bar Noy
Tzook Bar Noy

Reputation: 11677

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!

Upvotes: 15

Views: 18743

Answers (5)

M074554N
M074554N

Reputation: 71

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.

Upvotes: 3

Laurence
Laurence

Reputation: 60068

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

Upvotes: 8

tomvo
tomvo

Reputation: 1439

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

Upvotes: 33

Michael Dowling
Michael Dowling

Reputation: 5266

The previous answer is for Guzzle 3. Guzzle 5 uses the following:

<?php
$body = GuzzleHttp\Stream\Stream::factory('some mocked content');
$response = new Response(200, ['X-Foo' => 'Bar'], $body);

Upvotes: 12

Jacob Budin
Jacob Budin

Reputation: 10003

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

Upvotes: 4

Related Questions