zoukankan      html  css  js  c++  java
  • Laravel 单元测试-模拟认证的用户

    在 Laravel 编写单元测试时经常会遇到需要模拟认证用户的时候,比如新建文章、创建订单等,那么在 Laravel unit test 中如何来实现呢?

    官方解决方法

    Laravel 的官方文档中的测试章节中有提到:

    Of course, one common use of the session is for maintaining state for the authenticated user. The actingAs helper method provides a simple way to authenticate a given user as the current user. For example, we may use a model factory to generate and authenticate a user:

    <?php
    
    use AppUser;
    
    class ExampleTest extends TestCase
    {
        public function testApplication()
        {
            $user = factory(User::class)->create();
    
            $response = $this->actingAs($user)
                             ->withSession(['foo' => 'bar'])
                             ->get('/');
        }
    }
    

    其实就是使用 Laravel Testing IlluminateFoundationTestingConcernsImpersonatesUsers Trait 中的 actingAsbe 方法。

    设置以后在后续的测试代码中,我们可以通过 auth()->user() 等方法来获取当前认证的用户。

    伪造认证用户

    在官方的示例中有利用 factory 来创建一个真实的用户,但是更多的时候,我们只想用一个伪造的用户来作为认证用户即可,而不是通过 factory 来创建一个真实的用户。

    在 tests 目录下新建一个 User calss:

    use IlluminateFoundationAuthUser as Authenticatable;
    
    class User extends Authenticatable
    {
        protected $fillable = [
            'id', 'name', 'email', 'password',
        ];
    }
    

    必须在 $fillable 中添加 id attribute . 否则会抛出异常: IlluminateDatabaseEloquentMassAssignmentException: id

    接下来伪造一个用户认证用户:

    $user = new User([
        'id' => 1,
        'name' => 'ibrand'
    ]);
    
     $this->be($user,'api');
    

    后续会继续写一些单元测试小细节的文章,欢迎关注 : )

    讨论交流

    iBrand联系我们

  • 相关阅读:
    Vue3 模板语法
    Vue 起步
    [原创]CPA、CPC、CPM、CVR、CTR和ROI分别代表什么?
    Redis 线程模型
    BIO和NIO区别以及原理
    kafka简介&kafka安装
    python测试开发django-109.ModelForm模型表单的使用
    HttpRunner2.X 版本和 3.X 版本的区别到底有哪些?(吐血总结!)
    python测试开发django-108.form组件Select下拉框读取数据库内容
    DDD领域驱动设计架构模式:防腐层(Anti-corruption layer)
  • 原文地址:https://www.cnblogs.com/iBrand2018/p/10105787.html
Copyright © 2011-2022 走看看