lavaral5单元测试,post方式提交,方式无法进入

问题描述

在使用laravel5框架,写测试代码的时候,如果是POST方式提交的方法,方法不能正常调用,get方式则正常调用:
具体代码如下:
UserinfoTest:

public function testPostUserUpdate(){

    $user = new User(array('name' => 'qweqwe'));

    $this->be($user);

    $input = ['zbxname' =>'test','zbxpwd'=>'test'];

    $this->action('POST', 'UserinfoController@zbbixUserSet',$input);

    $this->action('get', 'UserinfoController@yyjrIndex');

    $this->assertResponseOk();

}

Routes:

Route::get('yyjrIndex','UserinfoController@yyjrIndex');
Route::post('zbbixUserSet','UserinfoController@zbbixUserSet');

解决方案:

第一种方式:

第一步:Session::start();
第二步:’_token’ => Session::token() 或者是 ‘_token’ => csrf_token(), // 手动加入 _token
$input = [‘zbxname’ =>’test’,’zbxpwd’=>’test’];

示例代码如下:

 //post测试方式一
    public function setUp(){
            parent::setUp();
            Session::start();// 开始session
    }
    public function testPostModifierPassword(){
        $user = new User(array('name' => 'qweqwe'));
        $this->be($user);
        $input = ['zbxname' =>'test','zbxpwd'=>'test'];
        $input['_token'] = csrf_token();
        $this->action('POST', 'UserinfoController@modifierPassword',$input);
        $this->assertResponseOk();
    }
    //post测试方式二
    public function testPostUserUpdate(){
        $user = new User(array('name' => 'qweqwe'));
        $this->be($user);
        Session::start();
        $input = ['zbxname' =>'test','zbxpwd'=>'test'];
        $input['_token'] = csrf_token();
        $this->action('POST', 'UserinfoController@zbbixUserSet',$input);
        $this->assertResponseOk();
    }

第二种方式

直接修改VerifyCsrfToken类中的验证方法,
参考网址:

第三种方式(不提倡)

1、在ApplicationTrait中,引入use Illuminate\Support\Facades\Session;
2、Illuminate\Foundation\Testing\ApplicationTrait中的action方法,
修改后为:

public function action($method, $action, $wildcards = [], $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
    {
        $uri = $this->app['url']->action($action, $wildcards, true);
        //maoch 添加_token
        if($method=='POST'){
            if(empty($wildcards['_token'])){
                $parameters['_token'] = Session::token();
            }
        }
        return $this->response = $this->call($method, $uri, $parameters, $cookies, $files, $server, $content);
    }

3、在测试方法中,添加setUp()方法,

public function setUp(){
        parent::setUp();
        Session::start();// 开始session
}

你可能感兴趣的:(laravel5)