2017-09-20 111 views
2

我想测试删除方法,但我没有从PHPUnit获得预期的结果。运行测试时,我收到此消息:PHPUnit:预期的状态代码200,但收到419与Laravel

Expected status code 200 but received 419. Failed asserting that false is true. 
/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:77 
/tests/Unit/CategoriesControllerTest.php:70 

Laravel版本:5.5

感谢您的帮助!

控制器构造:

public function __construct() 
{ 
    $this->middleware('auth'); 

    $this->middleware('categoryAccess')->except([ 
     'index', 
     'create' 
    ]); 
} 

控制器方法:

public function destroy($categoryId) 
{ 
    Category::destroy($categoryId); 

    session()->flash('alert-success', 'Category was successfully deleted.'); 

    return redirect()->action('[email protected]'); 
} 

categoryAccess中间件:

public function handle($request, Closure $next) 
{ 
    $category = Category::find($request->id); 

    if (!($category->user_id == Auth::id())) { 
     abort(404); 
    } 

    return $next($request); 
} 

分类模型:

protected $dispatchesEvents = [ 
    'deleted' => CategoryDeleted::class, 
]; 

事件监听

public function handle(ExpensesUpdated $event) 
{ 
    $category_id = $event->expense->category_id; 

    if (Category::find($category_id)) { 
     $costs = Category::find($category_id)->expense->sum('cost'); 

     $category = Category::find($category_id); 

     $category->total = $costs; 

     $category->save(); 
    } 
} 

PHPUnit的删除测试:

use RefreshDatabase; 

protected $user; 

public function setUp() 
{ 
    parent::setUp(); 
    $this->user = factory(User::class)->create(); 
    $this->actingAs($this->user); 
} 

/** @test */ 
public function user_can_destroy() 
{ 
    $category = factory(Category::class)->create([ 
     'user_id' => $this->user->id 
    ]); 

    $response = $this->delete('/category/' . $category->id); 

    $response->assertStatus(200); 

    $response->assertViewIs('category.index'); 
} 
+0

这是一个身份验证问题,试着用'$ this-> withoutMiddleware();'来看看它是否可以! – Maraboc

+0

嗨,我向该方法添加了该方法,然后再次运行测试,现在我收到了此消息:预期的状态代码为200,但收到302. – qwerty11

+0

尝试这次在PHPUnit类中使用Without'Middleware;'请不要忘记导入它'使用Illuminate \ Foundation \ Testing \ WithoutMiddleware;' – Maraboc

回答

1
在测试中,你需要禁用中间件进行

有时:

use Illuminate\Foundation\Testing\WithoutMiddleware; 

class ClassTest extends TestCase 
{ 
    use WithoutMiddleware; // use this trait 

    //tests here 
} 

,如果你只想禁用它们对于一个特定的测试用途:

$this->withoutMiddleware(); 
0

缓存配置文件时,可以通过运行php artisan config:clear来解决此问题。

相关问题