How to specify a different .env file for phpunit in Laravel 5?

前端 未结 10 2382
礼貌的吻别
礼貌的吻别 2020-12-29 05:25

I have a .env file containing my database connection details, as is normal for Laravel 5. I want to override these for testing, which I can do in phpunit.

10条回答
  •  盖世英雄少女心
    2020-12-29 06:10

    Been struggling with this for a few months now and just came across this Github issue today. From the solutions proposed there, here's what you should do in your CreatesApplication.php file (to delete the cached config in order to have Laravel load the test environment):

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';
    
        $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
    
        $this->clearCache(); // NEW LINE -- Testing doesn't work properly with cached stuff.
    
        return $app;
    }
    
    /**
     * Clears Laravel Cache.
     */
    protected function clearCache()
    {
        $commands = ['clear-compiled', 'cache:clear', 'view:clear', 'config:clear', 'route:clear'];
        foreach ($commands as $command) {
            \Illuminate\Support\Facades\Artisan::call($command);
        }
    }
    

    If you're still experiencing this issue after the above modification, you can go further by rebuilding the entire application as follows:

    public function createApplication()
    {
        $createApp = function() {
            $app = require __DIR__.'/../bootstrap/app.php';
            $app->make(Kernel::class)->bootstrap();
            return $app;
        };
    
        $app = $createApp();
        if ($app->environment() !== 'testing') {
            $this->clearCache();
            $app = $createApp();
        }
    
        return $app;
    }
    

    This is working just fine for me.

提交回复
热议问题