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



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

我的问题是现在我仍然无法弄清楚如何使其正常工作。我什至尝试过嘲笑它,但卡住了,因为 Yii 使用了很多静态方法来获取它的对象。当然,我现在可以尝试嘲笑他们了...但一定有更好的方法吗?

public function testSuccessFullFind(): void
{
$connection = (new Connection([
'dsn' => 'sqlite:test'
]))
->open();
$queryBuilder = new yiidbsqliteQueryBuilder($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) AuthenticationTestIdentifierResolverYii2ResolverTest::testSuccessFullFind
Error: Call to a member function getDb() on null
vendoryiisoftyii2-devframeworkdbActiveRecord.php:135
vendoryiisoftyii2-devframeworkdbActiveQuery.php:312
vendoryiisoftyii2-devframeworkdbQuery.php:237
vendoryiisoftyii2-devframeworkdbActiveQuery.php:133
testsTestCaseIdentifierResolverYii2ResolverTest.php:31

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

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

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

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

最新更新