【问题标题】:laravel 5 exception Illuminate\Session\TokenMismatchException in unit testlaravel 5 单元测试中的异常 Illuminate\Session\TokenMismatchException
【发布时间】:2015-02-13 12:23:08
【问题描述】:

我正在尝试编写一个测试来检查仅注册用户完成的一些活动。所以我需要通过 laravel 5 认证过程(带_token)

这是我的测试课

    class ImportTest extends TestCase {

            private $files = array();
            /**
             * Creates the application.

         *
         * @return \Illuminate\Foundation\Application
         */
        public function createApplication()
        {
                $app = require __DIR__.'/../bootstrap/app.php';

                $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

                return $app;
        }

        private function beTheUser(){

            $this->be(User::all()->first());
        }


        public function testAccessImportPageAjaxLoggedIn(){
            $this->beTheUser();
            $import = Import::all()->first();
            if($import!=null){
                $this->call('POST','ImportDocumentsController@status',array(
                    'import_id' => $import->id,
                    '_token' => Session::token()
                ));
                $this->assertResponseStatus('404');
            }


            $this->assertTrue(TRUE);
        }
}

当我尝试使用 phpunit test 测试函数时,我得到了 testing.ERROR:exception Illuminate\Session\TokenMismatchException

有人知道解决方法吗?

【问题讨论】:

  • 尝试在setUp()方法中添加Session::start()

标签: php unit-testing laravel laravel-5


【解决方案1】:

正如@lukasgeiter 发现的那样,一种可能的解决方案是写下这一行

        public function beTheUser {
            Session::start();
            $this->be(User::all()->first());

        }

我还需要在文件开头添加这一行。

use Session;

而不是 使用use Symfony\Component\HttpFoundation\Session\Session;

那么 在函数中需要时...

        $this->call('POST','/documents/import/'.$import->id,array(
            '_token' => Session::get('_token')
        ));
//or 


        $this->call('POST','/documents/import/'.$import->id,array(
            '_token' => Session::token()
        ));

【讨论】:

  • 不过你可以使用Session::token()
【解决方案2】:

运行php artisan config:clear。您的配置可能会被缓存,导致测试环境实际上指向您的本地环境

相关 Laracast 线程:https://laracasts.com/discuss/channels/laravel/laravelphpunit-testing-tokenmismatchexception#reply=486865

【讨论】:

    【解决方案3】:

    尝试使用 csrf_token() 代替 Session::token()。

    【讨论】:

    • csrf_token() 只是调用app('session')->token()
    猜你喜欢
    • 2016-06-22
    • 2015-09-13
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    相关资源
    最近更新 更多