代码之家  ›  专栏  ›  技术社区  ›  Fredrik

Laravel测试认证中间件

  •  0
  • Fredrik  · 技术社区  · 6 年前

    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 
    }
    

    然而,我发现像这样对每个需要身份验证的控制器进行测试是不必要的麻烦。

    使用auth中间件测试CRUD有什么策略吗?如何改进?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Fatemeh Majd    6 年前

    您可以使用数据提供程序:

    在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',
        ...
      ];
    }
    
        2
  •  0
  •   William ZOUNON    6 年前

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

    欧点 解决方案2 直接在路由上定义中间件

    Route::get('admin/profile', function () {
        //
    })->middleware('auth');
    

    https://laravel.com/docs/5.7/middleware

        3
  •  0
  •   Thijs Bouwes    6 年前

    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'));
        }
    }