californiamountainsnake / laravel-database-test-case
此包已被废弃且不再维护。未建议替代包。
此类用于测试需要与Laravel数据库连接的所有内容。
1.0.7
2020-10-06 14:46 UTC
Requires
- php: ^7.1
- ext-json: *
- ext-pdo: *
- laravel/framework: ^5.5||^6.0||^7.0||^8.0
Requires (Dev)
- ext-dom: *
- phpunit/phpunit: ^7.0
README
你想在真实数据库上测试你的模型、仓库、控制器吗?这个库可以帮助你!它可以创建临时用户和数据库,执行迁移并填充数据库。 并在测试完成后始终删除它们,即使出现异常和错误。当然,你的数据库也不会受到影响。
兼容性
此库支持 PHP ^7.1
以及多个Laravel版本:^5.5
、^6.0
、^7.0
、^8.0
。主要条件是:你必须有一个具有创建和删除其他用户和数据库权限的mysql用户(用于创建和删除临时用户和数据库)。
安装
使用Composer安装此包
通过 Composer 安装此包。编辑你的项目 composer.json
文件以添加 californiamountainsnake/laravel-database-test-case
。
{ "name": "yourproject/yourproject", "type": "project", "require": { "php": "^7.2", "californiamountainsnake/laravel-database-test-case": "*" } }
然后运行 composer update
或
在命令行中运行此命令
composer require californiamountainsnake/laravel-database-test-case
使用方法
扩展 AbstractDatabaseTestCase
类并实现抽象方法
<?php namespace Tests; use CaliforniaMountainSnake\LaravelDatabaseTestCase\AbstractDatabaseTestCase; class DatabaseTestCase extends AbstractDatabaseTestCase { /** * Load custom test dependencies. */ protected function initDependencies(): void { } /** * Get the database connection for the root user. * You are not required to provide a connection for the actual root user. * User of this connection just must have privileges to create and delete databases. * * @return string */ protected function getRootDbConnection(): string { return 'mysql'; } /** * Get the database connection that contains the migrations table. * * @return string */ protected function getMigrationDbConnection(): string { return 'mysql'; } /** * Get the array with databases connections that will be replaced to the test ones. * All test databases will be deleted after tests, also in a case of exceptions or errors. * * @return string[] */ protected function getMockedDbConnections(): array { return [ 'mysql', ]; } /** * Do we need to create temporary databases for the mocked connections before the tests? * Sometimes you create databases directly in the migrations. * * @return bool */ protected function isCreateMockedDatabases(): bool { return true; } /** * Get the absolute path to the /bootstrap/app.php. * * @return string */ public function getAppFilePath(): string { return __DIR__ . '/../bootstrap/app.php'; } }
就是这样!现在你可以从你的 DatabaseTestCase
扩展数据库测试,并使用你通常的模型执行数据库查询。
<?php namespace Tests\Feature; use Illuminate\Support\Facades\DB; use SebastianBergmann\RecursionContext\InvalidArgumentException; use Tests\DatabaseTestCase; class SimpleDatabaseTest extends DatabaseTestCase { /** * @throws InvalidArgumentException */ public function testGetUsers(): void { $users = DB::table('users')->get()->toArray(); // Gets users from the temp seeded database. $this->assertTrue(count($users) > 0); } }