guzzle php mock response content

Created on 16 Dec 2014  路  5Comments  路  Source: guzzle/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?

Most helpful comment

thanks @mtdowling,
I found this:

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

exactly as you said,
but just to mention that I browsed those docs before and after you send them again, and the

 Stream::factory

is never mentioned there...
so I would suggest to add it :+1:

All 5 comments

Why would you want to mock a response? Surely you should just create a normal response object?

I'm sorry I probably miss explained myself.

I perform a guzzle request:

 $response = $this->client->get(
            $url,
            ['query' => $data]
 );

and I want that this response will be the response I mock.

for example to mock it returned xml, json, simple string etc...

Take a look at these docs: http://docs.guzzlephp.org/en/latest/testing.html

You can create a body using GuzzleHttp\Stream\Stream::factory('foo').

thanks @mtdowling,
I found this:

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

exactly as you said,
but just to mention that I browsed those docs before and after you send them again, and the

 Stream::factory

is never mentioned there...
so I would suggest to add it :+1:

Was this page helpful?
0 / 5 - 0 ratings