【问题标题】:PHPUnit - REST API testingPHPUnit - REST API 测试
【发布时间】:2014-12-31 03:49:26
【问题描述】:


我有用 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


    【解决方案1】:

    您可以使用 Laravel 的内置方法 call 来测试您的控制器。

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

    您的ProgrammerControllerTest 应该从TestCase 扩展

    【讨论】:

    • 我意识到这是一个老问题和一个老答案,但是 OP 从来没有说过他们正在使用什么框架.. 假设他们使用 laravel 作为一个宁静的 api 并不是一个明智的假设而且真的没有回答他的问题....
    • @Logikos 可能是这种情况,但是我一直在寻找一个简单的、低开销的 Laravel POST 测试示例,使用 PHPUnit 和参数......这对我来说,回答了 我的问题。
    【解决方案2】:

    你可以试试

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

    这是我的 sn-p(它在 Get 但它是一样的)

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

    结果:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-09-08
        • 2021-04-04
        • 2012-07-16
        • 2017-09-25
        • 2019-08-06
        • 2021-06-04
        • 2014-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多