GuzzlePHP模拟响应内容

Tzo*_*Noy 8 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);
Run Code Online (Sandbox Code Playgroud)

我注意到我需要添加第三个参数接口:

 GuzzleHttp\Stream\StreamInterface
Run Code Online (Sandbox Code Playgroud)

但它有很多实现,我想返回一个简单的字符串.有任何想法吗?

编辑:现在我用这个:

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

但当我检查这个:

$response->getBody()->getContents()
Run Code Online (Sandbox Code Playgroud)

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

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

tom*_*mvo 29

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

use GuzzleHttp\Psr7;

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

  • 查看[Guzzle source](https://github.com/guzzle/psr7/blob/1.2.1/src/Response.php#L96),Response会自动为您执行此操作.只需传递一个字符串. (7认同)

Mic*_*ing 11

上一个答案适用于Guzzle 3. Guzzle 5使用以下内容:

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


Lau*_*nce 6

使用@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);
Run Code Online (Sandbox Code Playgroud)