在我的laravel 5.7.3应用程序中,我按照此处编写的方式进行自动测试 https://laravel.com/docs/5.7/http-tests
我创建了一个新用户,并在该新用户下打开了个人资料,并尝试修改此页面上可编辑的某些字段。 我在进行更改时出错:
"
Illuminate\Session\TokenMismatchException {#621
#message: ""
#code: 0
#file: "./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php"
#line: 82
trace: {
./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:82 { …}
./vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:223 { …}
...
./tests/Feature/ProfilepageTest.php:87 {
› $response = $this->actingAs($newUser)->get('/profile/edit-details');
› $response = $this->put( 'profile/edit-details-put', [ 'first_name' => 'Modified : '.$newUser->first_name, 'last_name' => 'Modified : '.$newUser->last_name, 'phone'=>'Modified : '.$newUser->phone, 'website'=>'Modified : '.$newUser->website, 'csrf_token'=> $csrf_token ]);
›
arguments: {
$uri: "profile/edit-details-put"
$data: array:5 [ …5]
}
}
./vendor/phpunit/phpunit/src/Framework/TestCase.php:1150 { …}
此错误是由我的代码触发的:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use DB;
use Illuminate\Foundation\Testing\WithFaker;
class ProfilePageTest extends TestCase // vendor/bin/phpunit tests/Feature/ProfilepageTest.php
{
public function testProfilePage()
{
$csrf_token = csrf_token();
...
$newUser = new User();
$newUser->username = 'Testing user on '.now();
$newUser->email = 'Testing_user_on_'.now().'@site.com';
...
$newUser->save();
$testing_user_id = $newUser->id;
...
$response = $this->actingAs($newUser)->get('/profile/edit-details');
$response = $this->put( 'profile/edit-details-put', [ 'first_name' => 'Modified : '.$newUser->first_name, 'last_name' => 'Modified : '.$newUser->last_name, 'phone'=>'Modified : '.$newUser->phone, 'website'=>'Modified : '.$newUser->website, 'csrf_token'=> $csrf_token ]);
...
}
}
在我的路线/web.php中:
Route::group(array('prefix' => 'profile', 'middleware' => ['auth', 'isVerified']), function(){
Route::put('edit-details-put', array(
'as' => 'profile-edit-details-put',
'uses' => 'ProfileController@update_details'
));
我使用Auth bad jrean / laravel-user-verification插件检查此URL。 在下一个的http-tests文档中:
The CSRF middleware is automatically disabled when running tests.
但是无论如何我都遇到了csrf错误。
为什么以及如何解决?
谢谢!