PHPUnit - REST API 测试

问题描述 投票:0回答:3


我有用 php 编写的 REST API,我想用 phpunit 测试它。

我像这样编写了测试,它有效,但响应正文为空。我用fiddler测试了它,它发送响应正文。

对不起我的英语。

class ProgrammerControllerTest extends PHPUnit_Framework_TestCase

{
    public function testPOST()
    {   

    // create our http client (Guzzle)
    $client = new Guzzle\Http\Client();
    $response = $client->post("http://api.loc/v2/", array(
    'headers' => "User-Agent: Fiddler\r\n" .
                "Host: api.loc\r\n".
                "Content-Type: application/x-www-form-urlencoded\r\n".
                "Content-Length: 34\r\n",
    'body'    => array('kle' =>'sino','lat' => '41', 'long' => '69'),
    ));
    var_dump($response);


    }
} 
rest phpunit guzzle
3个回答
0
投票

你可以尝试一下吗

var_dump($response->getBody()->getContents());

这是我的片段(它在 Get 中,但它是相同的)

$client = new GuzzleHttp\Client();
$response = $client->get('http://192.168.99.100/v1/hello');
var_dump($response->getBody()->getContents());

结果:

string(13) "{"bar":"foo"}"

-1
投票

您可以使用 Laravel 的内置方法

call
来测试您的控制器。

$response = $this->call('POST', '/api/v1.0/pages', $parameters);
$data = $response->getData();

您的

ProgrammerControllerTest
应从
TestCase

延伸

-1
投票

我知道 Amazon 使用 Guzzle 来测试 AWS SDK,您可以在 http://guzzle3.readthedocs.org/testing/unit-testing.html 阅读更多信息

而且,不要犹豫去挖掘其他人正在使用的东西(例如亚马逊、Facebook 等...),这就是开源如此伟大的原因!

© www.soinside.com 2019 - 2024. All rights reserved.