GuzzlePHP模拟响应内容

时间:2014-12-16 14:09:54

标签: php guzzle

我想模仿对Guzzle请求的回复:

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

我注意到我需要在界面中添加第三个参数:

 GuzzleHttp\Stream\StreamInterface

但它有很多实现,我想返回一个简单的字符串。有什么想法吗?

编辑:现在我用它:

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

但是当我检查这个时:

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

我得到一个空字符串。为什么是这样?

编辑2:只有当我使用xdebug时才会发生这种情况,当它正常运行时效果很好!

4 个答案:

答案 0 :(得分:27)

我们会继续这样做。上一个答案适用于Guzzle 5,这适用于Guzzle 6:

use GuzzleHttp\Psr7;

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

答案 1 :(得分:10)

之前的答案是针对Guzzle 3. Guzzle 5使用以下内容:

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

答案 2 :(得分:3)

Guzzle\Http\Message\Response允许您将第三个参数指定为字符串。

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

如果您更喜欢实施Guzzle\Stream\StreamInterface的解决方案,那么我建议您使用Guzzle\Http\EntityBody进行最简单的实施:

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

答案 3 :(得分:-2)

使用@tomvo答案和@Tim的评论 - 这就是我在Laravel应用程序中测试Guzzle 6所做的:

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