6

I have implemented a simple test to check whether a page is displayed in my application:

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class MyControllerTest extends WebTestCase
{
    public function testMyAction()
    {
        $client = static::createClient();
        $client->request('GET', '/');
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }
}

When I run php vendor/phpunit/phpunit/phpunit, I get the following error message:

1) App\Tests\Controller\MyControllerTest::testMyAction
Symfony\Component\DependencyInjection\Exception\EnvNotFoundException:
Environment variable not found: "DATABASE_URL".

Yet, this variable is available in .env. How can I solve this?

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • Are you using docker to run your test ? – kev.g Jan 26 '18 at 09:45
  • This is a sure fire sign that you've introduced a tight coupling somewhere. A unit test is supposed to test a unit in complete isolation from the rest of the system. If your unit test won't run without a particular environment variable set then that means it's not really testing a unit in isolation. The ```static::createClient()``` is a prime candidate for where your problem lies – GordonM Jan 26 '18 at 09:47
  • It should also be noted that in general you're not meant to unit test controllers. They're not meant to contain any meaningful business logic that needs testing in the first place and serve as little more than glue logic. If you feel a controller test is complex enough to require unit testing that might be a smell for an antipattern called "fat controller", where a controller contains business logic that really belongs elsewhere – GordonM Jan 26 '18 at 09:50
  • I am not using docker. – Jérôme Verstrynge Jan 26 '18 at 09:50
  • Your variable ```"DATABASE_URL"``` appear when you do ```env``` in your terminal ? – kev.g Jan 26 '18 at 09:53
  • 1
    @GordonM - Just for info, this is not a unit test. It is a functional test. https://symfony.com/doc/current/testing.html#functional-tests – Cerad Jan 26 '18 at 11:49
  • For me it was solved if I added this in the bottom of tests/bootstrap.php file: `(new Symfony\Component\Dotenv\Dotenv())->loadEnv(__DIR__.'/../.env');` The path depends where you .env files are of course. – Julesezaar Jan 30 '23 at 10:57

1 Answers1

12

I found the solution, it must be defined in phpunit.xml.dist, in the <php> section.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453