如何在库项目中测试 Yii2 模型?
How can I test a Yii2 model in a library project?
我正在尝试实现一个使用 Yii 模型对象扩展 yii\db\ActiveRecord
的适配器。该对象作为构造函数参数传递给适配器 class.
我现在的问题是我仍然无法弄清楚如何让它正常工作。我什至尝试过模拟它但卡住了,因为 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 对象使用它呢?
您可以将连接作为 all()
方法的参数传递:
$results = UserModel::find()->where(['id' => 1])->all($connection);
我正在尝试实现一个使用 Yii 模型对象扩展 yii\db\ActiveRecord
的适配器。该对象作为构造函数参数传递给适配器 class.
我现在的问题是我仍然无法弄清楚如何让它正常工作。我什至尝试过模拟它但卡住了,因为 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 对象使用它呢?
您可以将连接作为 all()
方法的参数传递:
$results = UserModel::find()->where(['id' => 1])->all($connection);