PHPUnit - Guzzle:API调用没有返回所需的响应

时间:2017-11-21 10:48:59

标签: php phpunit guzzle guzzle6

我正在使用PHPUnit和Guzzle来测试REST api,它在db中创建一条新记录,如果username(传入request参数)在db中已经不可用并且它发送JSON中的响应如下所示:

{
    "success": true,
    "id": "<unique_ID>"
}

如果username已经在db中可用,那么它会以JSON方式发送响应,如下所示:

{
    "success": false,
    "error": "username is already available"
}

这是我的PHPUnit测试用例,用于测试上面提到的API以及Guzzle:

  1. 这是一个setUp函数,用于设置Guzzle客户端

    public function setUp()
    {
        $this->client = new GuzzleHttp\Client([
            'base_uri' => 'http://localhost/test/'
        ]);
    }
    
  2. 这是实际的测试功能:

    public function testActualResult()
    {
        $response = $this->client->post('service.php', [
            'json' => [
                'operation' => 'create_user',
                'user_name' => 'testUser1'            
            ]
        ]);
    
        var_dump($response);
    }
    
  3. 每当我测试这个时,我会得到这样的反应:

    class GuzzleHttp\Psr7\Response#99 (6) {
      private $reasonPhrase =>
      string(2) "OK"
      private $statusCode =>
      int(200)
      private $headers =>
      array(5) {
        'Date' =>
        array(1) {
          [0] =>
          string(29) "Tue, 21 Nov 2017 10:27:22 GMT"
        }
        'Server' =>
        array(1) {
          [0] =>
          string(47) "Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31"
        }
        'X-Powered-By' =>
        array(1) {
          [0] =>
          string(10) "PHP/5.6.31"
        }
        'Content-Length' =>
        array(1) {
          [0] =>
          string(4) "1357"
        }
        'Content-Type' =>
        array(1) {
          [0] =>
          string(16) "application/json"
        }
      }
      private $headerNames =>
      array(5) {
        'date' =>
        string(4) "Date"
        'server' =>
        string(6) "Server"
        'x-powered-by' =>
        string(12) "X-Powered-By"
        'content-length' =>
        string(14) "Content-Length"
        'content-type' =>
        string(12) "Content-Type"
      }
      private $protocol =>
      string(3) "1.1"
      private $stream =>
      class GuzzleHttp\Psr7\Stream#86 (7) {
        private $stream =>
        resource(408) of type (stream)
        private $size =>
        NULL
        private $seekable =>
        bool(true)
        private $readable =>
        bool(true)
        private $writable =>
        bool(true)
        private $uri =>
        string(10) "php://temp"
        private $customMetadata =>
        array(0) {
        }
      }
    }
    

    但是我没有得到API调用本身发回的所需响应。

    如果我使用POSTMAN测试我上面提到的API,它会完美运行并返回所需的响应。

1 个答案:

答案 0 :(得分:2)

您是否阅读过GuzzlePHP documentation?在“快速启动”下 - &gt; “使用回复”描述了当您想要获得回复的正文时,您需要使用getBody()上的$response函数。

你正在做的只是转储整个请求变量,其中包含了你想要做的事情所需的更多信息。

有关示例,请参阅Using Responses

$response = $client->post('your parameters here');
$body = $response->getBody();
echo $body;