使用JSON请求体测试laravel控制器

Rei*_*dsy 11 phpunit laravel angularjs laravel-3

我正在尝试为Laravel控制器编写一个phpunit测试,该控制器期望使用JSON格式的主体发布请求.

控制器的简化版本:

class Account_Controller extends Base_Controller
{
    public $restful = true;

    public function post_login()
    {
        $credentials = Input::json();
        return json_encode(array(
            'email' => $credentials->email,
            'session' => 'random_session_key'
        ));
    }
}
Run Code Online (Sandbox Code Playgroud)

目前我有一个测试方法正确地将数据作为urlencoded表单数据发送,但我无法弄清楚如何将数据作为JSON发送.

我的测试方法(我用的是GitHub的要点在这里写测试时)

class AccountControllerTest extends PHPUnit_Framework_TestCase {
    public function testLogin()
    {
        $post_data = array(
            'email' => 'user@example.com',
            'password' => 'example_password'
        );
        Request::foundation()->server->set('REQUEST_METHOD', 'POST');
        Request::foundation()->request->add($post_data);
        $response = Controller::call('account@login', $post_data);
        //check the $response
    }
}
Run Code Online (Sandbox Code Playgroud)

我在前端使用angularjs,默认情况下,发送到服务器的请求是JSON格式.我宁愿不改变它发送urlencoded形式.

有谁知道如何编写一个为控制器提供JSON编码体的测试方法?

car*_*lve 7

这就是我在Laravel4中这样做的方法

// Now Up-vote something with id 53
$this->client->request('POST', '/api/1.0/something/53/rating', array('rating' => 1) );

// I hope we always get a 200 OK
$this->assertTrue($this->client->getResponse()->isOk());

// Get the response and decode it
$jsonResponse = $this->client->getResponse()->getContent();
$responseData = json_decode($jsonResponse);
Run Code Online (Sandbox Code Playgroud)

$responseData 将是一个等于json响应的PHP对象,然后允许您测试响应:)


eoi*_*noc 6

在Laravel 5中,call()方法已经改变:

$this->call(
    'PUT', 
    $url, 
    [], 
    [], 
    [], 
    ['CONTENT_TYPE' => 'application/json'],
    json_encode($data_array)
);
Run Code Online (Sandbox Code Playgroud)

我认为Symphony的request()方法被称为:http: //symfony.com/doc/current/book/testing.html


Aar*_*ock 5

这对我有用.

$postData = array('foo' => 'bar');
$postRequest = $this->action('POST', 'MyController@myaction', array(), array(), array(), array(), json_encode($postData));
$this->assertTrue($this->client->getResponse()->isOk());
Run Code Online (Sandbox Code Playgroud)

第七个论点$this->actioncontent.请参阅http://laravel.com/api/source-class-Illuminate.Foundation.Testing.TestCase.html#_action上的文档


Nav*_*een 2

有更简单的方法可以做到这一点。您只需将 Input::$json 属性设置为要作为 post 参数发送的对象即可。请参阅下面的示例代码

 $data = array(
        'name' => 'sample name',
        'email' => 'abc@yahoo.com',
 );

 Input::$json = (object)$data;

 Request::setMethod('POST');
 $response = Controller::call('client@create');
 $this->assertNotNull($response);
 $this->assertEquals(200, $response->status());
Run Code Online (Sandbox Code Playgroud)

我希望这对您的测试用例有所帮助

更新:原始文章可以在这里找到http://forums.laravel.io/viewtopic.php?id=2521

  • 当我尝试此操作时,我收到“致命错误:访问未声明的静态属性:Illuminate\Support\Facades\Input::$json” - 我是否缺少一些上下文? (3认同)