[英]Laravel Testing auth middleware
在對應用程序進行功能測試時,我發現自己編寫了幾乎相同的測試來驗證我的控制器是否需要身份驗證。 通常看起來像這樣:
public function a_guest_cannot_view_any_of_the_pages()
{
$this->withExceptionHandling();
$model = factory(Model::class)->create();
$response = $this->get(route('models.show', [ 'id' => $model->id ]));
$response->assertRedirect(route('login'));
$response = $this->get(route('models.edit', [ 'id' => $model->id ]));
$response->assertRedirect(route('login'));
...etc
}
但是,我發現對每個需要身份驗證的控制器進行這樣的測試都不必要地麻煩。
使用身份驗證中間件測試CRUD是否有任何策略? 我該如何改善?
您可以使用數據提供程序:
在tests / TestCase.php中:
/**
* @dataProvide dataProvider
*/
public function testRedirectToAuth($routeName)
{
$this->withExceptionHandling();
$model = factory(Model::class)->create();
$response = $this->get(route($routeName, [ 'id' => $model->id ]));
$response->assertRedirect(route('login'));
}
然后您可以在所有測試用例中調用它:
public function dataProvider()
{
return [
'model.show',
'model.edit',
...
];
}
解決方案1在控制器構造函數中定義將對所有功能起作用的中間件
public function __construct()
{
$this->middleware('auth');
}
解決方案2在路徑上直接定義中間件
Route::get('admin/profile', function () {
//
})->middleware('auth');
您可以使用ShowTrait
,使用此特征時,您必須指定您的路線和模型名稱。
<?php
class ModelTest extends Test
{
use ShowTrait;
protected $routebase = 'api.v1.models.';
protected $model = Model::class;
}
abstract class Test extends TestCase
{
use RefreshDatabase, InteractsWithDatabase, UseAuthentication;
protected $routebase = 'api.v1.';
protected $model;
/**
* @test
*/
public function is_valid_model()
{
$this->assertTrue(class_exists($this->model));
}
}
trait ShowTrait {
public function test_show_as_authenticated_user()
{
$record = factory($this->model);
$this->assertShow($record)
}
protected function assertShow($record)
{
$route = route($this->routebase . "show", ['id' => $record->id]);
// Get response
$response = $this->get($route);
$response->assertRedirect(route('login'));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.