简体   繁体   中英

How to mock response from file using Guzzle 6?

Here is the content of response.txt :

HTTP/1.1 200 OK
Server: nginx
Date: Fri, 15 Feb 2016 18:25:28 GMT
Content-Type: application/json;charset=utf-8

{
  "field1": "a",
  "field2": "b",
}

I tried:

$stream = Psr7\stream_for(file_get_contents('response.txt'));
$response = new Response(200, ['Content-Type' => 'application/json'], $stream);
dd($response->getBody());

Which output:

object(GuzzleHttp\Psr7\Stream)#3 (7) {
  ["stream":"GuzzleHttp\Psr7\Stream":private]=>
  resource(26) of type (stream)
  ["size":"GuzzleHttp\Psr7\Stream":private]=>
  NULL
  ["seekable":"GuzzleHttp\Psr7\Stream":private]=>
  bool(true)
  ["readable":"GuzzleHttp\Psr7\Stream":private]=>
  bool(true)
  ["writable":"GuzzleHttp\Psr7\Stream":private]=>
  bool(true)
  ["uri":"GuzzleHttp\Psr7\Stream":private]=>
  string(10) "php://temp"
  ["customMetadata":"GuzzleHttp\Psr7\Stream":private]=>
  array(0) {
  }
}

So I can not get the JSON content in response.txt , how to do that? What I want to get is something like:

array('field1'=>'a','field2'=>'b');

The third parameter to the Response class constructor should be the body string. See the documentation for the Guzzle Response class: http://docs.guzzlephp.org/en/latest/psr7.html#guzzle-and-psr-7 .

The following code should work:

$stream = file_get_contents('response.txt');
$response = new Response(200, ['Content-Type' => 'application/json'], $stream);
dd($response->getBody());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM