'In Laravel, how can I clear my database after my test class is done running?
I have a really large database that I want to introduce testing into and I have been experimenting on ways to approach it.
If I were to run the full migrate:fresh it would take about a minute to create the entire schema. To seed this database it would likely take >5 minutes. My thought was to preload a DB schema into a test database ahead of time, before the tests even start running. Then I was thinking I would seed portions of data as I need it.
This project has multiple domains and it is a DDD design. I'm currently thinking that each domain will have at least one testcase that extends laravels BaseTestcase.
The problem I'm having is that I am not able to clear the data from the database. Here's an example of what a testcase might look like for one of my domains:
use CreatesApplication;
use RefreshDatabase;
use ActingAsUser;
use HasTestHelpers;
/**
* Refresh a conventional test database.
*
* @return void
*/
protected function refreshTestDatabase()
{
if (! RefreshDatabaseState::$migrated) {
$this->artisan('db:seed --class=CourseTestSeeder');
$this->app[Kernel::class]->setArtisan(null);
RefreshDatabaseState::$migrated = true;
}
$this->beginDatabaseTransaction();
}
public static function tearDownAfterClass(): void
{
CourseTestSeeder::clear();
}
This particular domains depends on Course data. I put together a CourseTestSeeder that will seed all the data needed for this domain. This part works great. The problem is that when I try to do a tearDownAfterClass I receive the following error:
Exception in tearDownAfterClass
Target class [db] does not exist.
at vendor/phpunit/phpunit/phpunit:98
94▕ unset($options);
95▕
96▕ require PHPUNIT_COMPOSER_INSTALL;
97▕
➜ 98▕ PHPUnit\TextUI\Command::main();
99▕
How can I clear the db after my tests run? Is there a better way to do this?
If this is not a good approach, I also welcome feedback on that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
