PHPUnit:预期状态码为200,但Laravel收到419 [英] PHPUnit: Expected status code 200 but received 419 with Laravel
本文介绍了PHPUnit:预期状态码为200,但Laravel收到419的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想测试delete方法,但是我没有从PHPUnit获得预期的结果.运行测试时,我收到此消息:
I want to test the delete method but I am not getting the expected results from PHPUnit. I receive this message when running the test:
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
Laravel version: 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('CategoriesController@index');
}
categoryAccess中间件:
categoryAccess middleware:
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删除测试:
PHPUnit delete test:
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');
}
推荐答案
有时在测试中,您需要禁用中间件才能继续:
Sometimes in testing you will need to disable middlewares to proceed :
use Illuminate\Foundation\Testing\WithoutMiddleware;
class ClassTest extends TestCase
{
use WithoutMiddleware; // use this trait
//tests here
}
,如果您只想针对一种特定的测试禁用它们:
and if you want to disable them just for one specific test use :
$this->withoutMiddleware();
这篇关于PHPUnit:预期状态码为200,但Laravel收到419的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文