【发布时间】:2018-03-01 17:38:57
【问题描述】:
我想测试删除方法,但我没有从 PHPUnit 获得预期的结果。我在运行测试时收到此消息:
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('CategoriesController@index');
}
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();看看会不会OK!! -
您好,谢谢,我将其添加到方法中并再次运行测试,我现在收到此消息:预期状态代码 200 但收到 302。
-
这次试试 PHPUnit 类中的
use WithoutMiddleware;,别忘了导入它use Illuminate\Foundation\Testing\WithoutMiddleware; -
谢谢@Maraboc $this->withoutMiddleware();作品!问题是这个测试应该期待状态码 302 我通过阅读来自 here 的答案发现的。
-
很高兴知道 ;)