我正在尝试实现一个使用扩展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对象使用它?
答案 0 :(得分:0)
您可以将连接作为all()
方法的参数传递:
$results = UserModel::find()->where(['id' => 1])->all($connection);