如何在编码单元测试案例中使用YII2用户身份



我是单位测试的新手。尝试在我的YII2项目中使用CodeCeption插件创建一些测试用例。从过去的1周开始,我正在学习它。

现在我知道如何在单元测试中使用固定装置,模拟和存根。

我只想问,在某些情况下,我们可以在单元测试中使用YII2用户身份类。例如,可能有情况是我们必须检查某些条件以登录用户。在这种情况下,如何在单元测试中使用用户会话或用户身份。

单元测试的想法是测试代码的单个特定部分,例如函数或方法。如果您测试具有依赖项的功能或方法,例如获取用户ID或数据库记录,则单位测试的目的是模拟或固态方法的每个依赖项。

另一种方法是在测试中重建/重建/重建自举应用程序。在您的情况下,这意味着:调用正确的方法来创建用户对象,例如通过调用登录方法。

如果您想测试应用程序的整个部分,而不是-Maybe-功能测试是适合您的情况的测试类型。在这里,您从一个完整的自举应用程序开始,您可以在其中首先登录用户(调用用户页面(并执行测试柜。

但是:
如果您在测试中只需要任何登录名,则还可以为测试定义虚拟用户类。这意味着:

  1. config/test.php中添加类似的东西用于使用虚拟用户模型:

    '用户'=>['IdentityClass'=>'app tests models dummyuser','loginurl'=>['站点/登录'],'enableautologin'=>真的,'启用'=>真的,],

  2. apptestsmodelsDummyUser中创建一个虚拟用户模型,该模型实现了IdentityIngterface所需的所有方法,例如:

    名称空间应用 Tests Models;

    使用yii web sidentityInterface;使用app models user;

    类dummyuser扩展了用户实施IdentityInterface{public $ id =; foo"

     public static function findIdentity($id)
     {   
         // always return the same dummy user
         return new static ([
             'id' => 'dummyUser',
             'email' => 'dummyUser@domain',
             'name' => 'Dummy User'
         ]);
     }
     public static function findGuestIdentity()
     {
          return new static ([
             'id' => 'guest',
             'email' => '',
             'name' => 'Guest User'
         ]);
     }
     public static function findGast()
     {
         return new static ([
             'id' => 'guest'
         ]);
     }
     /**
      * This method is needed to satisfy the interface.
      * {@inheritdoc}
      */
     public static function findIdentityByAccessToken($token, $type = null)
     {
         return true;
     }
     /**
      * This method is needed to satisfy the interface.
      * 
      * {@inheritdoc}
      */
     public function getId()
     {
         return true;
     }
     /**
      * This method is needed to satisfy the interface.
      * {@inheritdoc}
      */
     public function getAuthKey()
     {
         return "bar";
     }
     /**
      * This method is needed to satisfy the interface.
      * {@inheritdoc}
      */
     public function validateAuthKey($authKey)
     {
         return true;
     }
    

    }

  3. 在您的单元测试中使用Yii和您的虚拟用户模型use apptestmodelsDummyUser,并在测试阶段之前运行一个假登录:

    受保护函数_before(({$ Dummylogin = Dummyuser :: FindIdentity('Dummyuser'(;yii :: $ app-> user-> login($ dummylogin(;}

现在,YII2用户身份可在YII2 CodeCeption单元测试中获得。现在,您有一个(伪造的(登录YII2中的单位测试。

最新更新