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');
}
这是一个身份验证问题,试着用'$ this-> withoutMiddleware();'来看看它是否可以! – Maraboc
嗨,我向该方法添加了该方法,然后再次运行测试,现在我收到了此消息:预期的状态代码为200,但收到302. – qwerty11
尝试这次在PHPUnit类中使用Without'Middleware;'请不要忘记导入它'使用Illuminate \ Foundation \ Testing \ WithoutMiddleware;' – Maraboc