Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GuzzlePHP mock response content

Tags:

php

guzzle

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!

like image 374
Tzook Bar Noy Avatar asked Dec 16 '14 14:12

Tzook Bar Noy


2 Answers

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);
like image 54
Michael Dowling Avatar answered Nov 05 '22 06:11

Michael Dowling


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);
like image 32
tomvo Avatar answered Nov 05 '22 04:11

tomvo