Laravel 测试认证中间件

弗雷德里克

在对我的应用程序进行功能测试时,我发现自己编写了几乎相同的测试来验证我的控制器是否需要身份验证。它通常看起来像这样:

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 的策略?我该如何改进?

法蒂梅·马吉德

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

在测试/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',
    ...
  ];
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章