PHPUnit Guzzle响应不起作用

时间:2016-10-14 05:05:52

标签: php unit-testing phpunit guzzle

我开始使用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) {
  }
}

1 个答案:

答案 0 :(得分:0)

来自docs

  

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

另外,看看Guzzle代码,它很清楚它返回了一个实现public class ContactActivity extends Activity implements ContactListFragment.ContactListListener{ @Override public void itemClicked(long id){ //method also defined in the listener View fragmentContainer = findViewById(R.id.fragment_detail_container); //here instanciate the fragment and commit } } 的对象:

StreamInterface

你需要的是使用/** * Get the body of the message * * @return StreamInterface|null */ public function getBody(); 方法解析并返回JSON响应体(已经解码)。请尝试以下方法:

json()