单元测试laravel 4控制器传递JSON有效负载

时间:2013-08-23 19:14:09

标签: laravel phpunit laravel-4

应用程序/控制器/ SecurityController.php

class SecurityController extends Controller { 

    public function login()
    {       
        $payload = file_get_contents("php://input");
        $payload = json_decode($payload);

        $input = array('mail' => $payload->mail, 
                       'password' => $payload->password,
                 );


        if (Auth::attempt($input))
        {
        }
     }
}

应用程序/测试/ SecurityTest.php

class SecurityTest extends TestCase {
    public function testLogin()
    {
        $data = array(
            'mail' => 'test@test.com',
            'password' => 'mypasswprd',
        );

        $crawler = $this->client->request('POST', '/v2/login', $data);
    }

当我运行phpunit时,我收到此错误: 。{“error”:{“type”:“ErrorException”,“message”:“试图获取非对象的属性”,“file”:app / controllers / SecurityController.php“,”line“:20}}

1 个答案:

答案 0 :(得分:1)

您为什么使用file_get_contents("php://input")? Laravel允许您使用Input:get()方法,这是从表单或json检索输入数据的简单方法。我打赌它会更容易测试。

您的控制器应该是这样的:

class SecurityController extends Controller { 

    public function login()
    {       
        $input = array(
            'mail'     => Input::get('mail'), 
            'password' => Input::get('password'),
        );

        if (Auth::attempt($input))
        {
        }
    }
}