【问题标题】:PHPUnit Guzzle Response not workingPHPUnit Guzzle 响应不起作用
【发布时间】:2023-03-10 03:45:01
【问题描述】:

我开始使用 PHPUnit 和 Guzzle 来测试一些 API,但是当我运行以下单元测试时,我没有收到正确的 json。代码有什么问题?

<?php

require('vendor/autoload.php');

class TestAll extends PHPUnit_Framework_TestCase
{
    protected $client;

    protected function setUp()
    {
        $this->client = new GuzzleHttp\Client([
            'base_uri' => 'https://url',
            'verify'  => false,
            'headers' => ['Accept' => 'application/json']

            ]);
    }

    public function testGet_ValidInput_TestAllObject()
    {
        $response = $this->client->get('/test_all');
        var_dump($response->getBody());
        $this->assertEquals(200, $response->getStatusCode());
        $data = json_decode($response->getBody(), true);

    }
}

这是我得到的:

    .                                                                   1 / 1 (100%)object(GuzzleHttp\Psr7\Stream)#39 (7) {
  ["stream":"GuzzleHttp\Psr7\Stream":private]=>
  resource(1127) 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) {
  }
}

【问题讨论】:

    标签: php unit-testing phpunit guzzle


    【解决方案1】:

    来自docs

    可以通过调用 $response->getBody() 来检索响应的实体主体对象。

    另外,查看 Guzzle 代码,很明显它返回了一个实现 StreamInterface 的对象:

    /**
     * Get the body of the message
     *
     * @return StreamInterface|null
     */
    public function getBody();
    

    您需要使用 json() 方法解析并返回 JSON 响应正文(已解码)。请尝试以下操作:

    public function testGet_ValidInput_TestAllObject()
    {
        $response = $this->client->get('/test_all');
        $this->assertEquals(200, $response->getStatusCode());
        $data = $response->json();
        var_dump($data);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-08
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2017-01-05
      • 2019-01-21
      • 2016-10-04
      • 2013-11-05
      相关资源
      最近更新 更多