Friday 2 October 2015

Using Testing Environment with PHPunit and Laravel

Hello,

Recently I've been using phpunit with Laravel and I found this problem: How to clean or reset my test environment on every test? I did this solution:

Laravel version : 5.1

I followed this tutorial: http://laravel.com/docs/5.1/testing

I created my .env.testing file:

APP_ENV=testing
APP_DEBUG=true
APP_KEY=app_key_testing

DB_CONNECTION=mysql_testing
DB_HOST=localhost
DB_DATABASE=test
DB_USERNAME=dbusernametest
DB_PASSWORD=dbpwdtest

I changed my TestCase.php file:

class TestCase extends Illuminate\Foundation\Testing\TestCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

        return $app;
    }

    public function setUp()
    {
        exec('cp /opt/lampp/htdocs/mytestsite/.env.testing /opt/lampp/htdocs/mytestsite/.env');
        parent::setUp();
        Artisan::call('migrate');
    }

    public function tearDown()
    {
        Artisan::call('migrate:reset');
        parent::tearDown();
        exec('cp /opt/lampp/htdocs/mytestsite/.env.local /opt/lampp/htdocs/mytestsite/.env');
    }
}

I hope you find it useful.

Best regards!

No comments:

Post a Comment