2

I wanted to refresh my testing database once per class instead of per test using the setUpBeforeClass method. As it is static, I can't call $this->artisan() therefore I tried to use Artisan::call() with facades.

The problem is that facades are not working here. I receive the error A facade root has not been set. even though I uncommented $app->withFacades(); from bootstrap/app.php.

How can I call an artisan command inside setUpBeforeClass?

Here is my test class:

<?php

use Illuminate\Support\Facades\Artisan;

class ExampleTest extends TestCase
{
    public static function setUpBeforeClass(): void
    {
        parent::setUpBeforeClass();

        Artisan::call('migrate:fresh');
        Artisan::call('db:seed --no-interaction');
    }

    public function testOne()
    {
        $this->assertTrue(true);
    }
}
guizo
  • 2,594
  • 19
  • 26
  • AFAIK it's not possible to call an artisan command in `setUpBeforeClass`. Interesting question thought, how did you came to a different conclusion? – hakre Jun 14 '21 at 18:00
  • 1
    I didn't came to a different solution. I was hopping that there was a way to call a artisan command once per file but apparently in `setUpBeforeClass` it is not possible - just saw this answer and it makes sense - https://stackoverflow.com/a/46453228/6453726. Don't know how this could be achieve but I believe it would be very useful. I posted this as an `Idea` in the Laravel repository - https://github.com/laravel/framework/discussions/37980 Thanks. – guizo Jul 11 '21 at 23:25
  • 1
    That sounds reasonable to me nad I've taken a quick look at the post to the idea forum. You perhaps could edit in a little bit of the code to your post there so that its more clear what you're after without the need to leave the discussion there (e.g. the `setUpBeforeClass` methods code). – hakre Jul 12 '21 at 04:54
  • Good idea. I updated the text. If you can and wan't to, please up vote the idea in GitHub. Thank you. – guizo Jul 12 '21 at 11:13
  • @guizo you should be using the trait [`DatabaseMigrations`](https://github.com/laravel/lumen-framework/blob/8.x/src/Testing/DatabaseMigrations.php) same as `Laravel`... But this will only run `migrate:fresh`. For `db:seed`, you should either run that on `setUp` or create a method that will call for that when you begin the test... – matiaslauriti Aug 17 '21 at 06:22

0 Answers0