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

问题描述 投票:0回答:1

我正在尝试实现一个使用扩展yii\db\ActiveRecord的Yii模型对象的适配器。该对象作为构造函数arg传递给适配器类。

我现在的问题是,我仍然无法弄清楚如何让它正常工作。我甚至尝试过嘲笑但是因为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

上面的代码显然是测试用例的WIP。

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

unit-testing activerecord yii yii2 phpunit
1个回答
0
投票

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

$results = UserModel::find()->where(['id' => 1])->all($connection);
© www.soinside.com 2019 - 2024. All rights reserved.