测试REST get请求

时间:2014-06-03 11:50:19

标签: rest phpunit slim

如何使用PHPUnit 4.1 测试REST API的GET请求?我使用Slim PHP-Framework,可以设法测试响应代码,但不测试正文或标题。 这就是我到目前为止所做的:

TestClass:

class AssetTest extends PHPUnit_Framework_TestCase
{

public function request($method, $path, $options = array())
{
    // Capture STDOUT
    ob_start();

    // Prepare a mock environment
    Environment::mock(array_merge(array(
        'REQUEST_METHOD' => $method,
        'PATH_INFO' => $path,
        'SERVER_NAME' => 'slim-test.dev',
    ), $options));

    $app = new \Slim\Slim();
    $this->app = $app;
    $this->request = $app->request();
    $this->response = $app->response();

    // Return STDOUT
    return ob_get_clean();
}

   public function get($path, $options = array()){
      $this->request('GET', $path, $options);
   }

   public function testGetAssets(){
      $this->get('/asset');
      $this->assertEquals('200', $this->response->status());
   }
}

如果http://example.com/asset的JSON响应如下(代码200):

[
  {
    "AssetID": "4b0be88b9e853",
    "AssetStatusID": "1"
  }
]

1 个答案:

答案 0 :(得分:0)

一切都很好。要获得响应的主体,请致电 $response->getBody()并使用json_decode解码此响应。要获取标题,请调用$response->getHeaders()

在你的情况下,它将由$this->response->getBody()。所以你的考试 方法将如下所示

public function testGetAssets(){
        $this->get('/asset');
        $response = json_decode($this->response->getBody(), true); //response body
        $headers = $this->response->getHeaders()  //response headers
        $this->assertEquals('200', $this->response->status());
    }

这个答案是关于guzzlehttp的最新版本,即6.0