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

如何在库项目中测试Yii2模型?

  •  0
  • floriank  · 技术社区  · 7 年前

    yii\db\ActiveRecord . 对象作为构造函数参数传递给适配器类。

    我现在的问题是,我仍然不知道如何让它正常工作。我甚至尝试过模仿它,但是因为Yii使用了很多静态方法来获取它的对象而被卡住了。当然,我现在可以试着嘲笑他们。。。但一定有更好的办法?

    public function testSuccessFullFind(): void
    {
        $connection = (new Connection([
                'dsn' => 'sqlite:test'
            ]))
            ->open();
    
        $queryBuilder = new \yii\db\sqlite\QueryBuilder($connection);
    
        $app = $this->createMock(Application::class);
        \Yii::$app = $app;
    
        $app->expects($this->any())
            ->method('getDb')
            ->willReturn($this->returnValue($connection));
    
        $userModel = new UserModel();
        $resovler = new Yii2Resolver($userModel);
        $result = $resolver->find(['username' => 'test', 'password' => 'test']);
        // TBD asserts for the result
    }
    

    UserModel 用于在内部查找用户记录。

    这将导致:

    1) Authentication\Test\Identifier\Resolver\Yii2ResolverTest::testSuccessFullFind
    Error: Call to a member function getDb() on null
    
    vendor\yiisoft\yii2-dev\framework\db\ActiveRecord.php:135
    vendor\yiisoft\yii2-dev\framework\db\ActiveQuery.php:312
    vendor\yiisoft\yii2-dev\framework\db\Query.php:237
    vendor\yiisoft\yii2-dev\framework\db\ActiveQuery.php:133
    tests\TestCase\Identifier\Resolver\Yii2ResolverTest.php:31
    

    那么,如何配置测试连接并让ActiveRecord对象使用它呢?

    1 回复  |  直到 7 年前
        1
  •  0
  •   rob006    7 年前

    您可以传递连接作为的参数 all() 方法:

    $results = UserModel::find()->where(['id' => 1])->all($connection);
    
    推荐文章