【问题标题】:testing a POST using phpunit in laravel 4在 laravel 4 中使用 phpunit 测试 POST
【发布时间】:2014-09-11 12:36:39
【问题描述】:

我有一条通过 POST 来创建数据的路线,我正在尝试测试是否一切都应该按应有的方式工作。

我有一个 json 字符串,其中包含我想要测试的值,但到目前为止,当我使用 phpunit 运行测试时,测试总是失败:

另外,我知道 json 字符串只是一个字符串,但我也不确定如何使用 json 字符串来测试输入。

我的路线:

Route::post('/flyer', 'flyersController@store');

 public function testFlyersCreation()
{
    $this->call('POST', 'flyers');

    //Create test json string
    $json = '{ "name": "Test1", "email": "test@gmail.com", "contact": "11113333" }';

    var_dump(json_decode($json));



}

当我运行 phpunit 时,我的错误指向显示“未定义索引:名称”的调用 POST

【问题讨论】:

    标签: php json laravel-4 phpunit


    【解决方案1】:

    我不确定我是否正确理解了这个问题,因为代码示例实际上什么都不做,但是如果您问如何测试请求中需要 json 数据的发布路由,请查看调用() 方法:

    https://github.com/laravel/framework/blob/4.2/src/Illuminate/Foundation/Testing/ApplicationTrait.php

    原始帖子数据应该在 $content 变量中。

    我没有安装 Laravel 4 来测试它,但它在 Laravel 5 中对我有用,其中函数的参数顺序略有不同:

    public function testCreateUser()
    {
        $json = '
        {
            "email" : "horst.fuchs@example.com",
            "first_name" : "Horst",
            "last_name" : "Fuchs"
        }';
    
        $response = $this->call('POST', 'user/create', array(), array(), array(), array(), $json);
    
        $this->assertResponseOk();
    }
    

    【讨论】:

      【解决方案2】:

      如果你查看TestCase的源代码你可以看到方法实际上是在调用

      call_user_func_array(array($this->client, 'request'), func_get_args());

      所以这意味着你可以做这样的事情

      $this->client->request('POST', 'flyers', $json );

      然后你检查响应

      $this->assertEquals($json, $this->client->getResponse());

      你得到的错误可能是控制器抛出的,因为它没有收到任何数据

      【讨论】:

      • hmm,我试过了,在 $json 的请求中,我输入了一个解码的 $json 字符串,它要求一个数组,但是当我把它变成一个数组时,它要求一个字符串。
      • 嗯,好的,$client 是 api.symfony.com/2.0/Symfony/Component/HttpKernel/Client.html。所以尝试这样 $this->client->request('POST', 'flyers', null, null, null, $json);
      猜你喜欢
      • 2014-09-12
      • 2013-09-13
      • 2013-04-14
      • 2015-01-24
      • 2014-09-21
      • 2013-10-26
      • 2014-09-11
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多