Xml – Why phpunit is not getting the correct APP_ENV as specified in phpunit.xml

dockerlaravelphpunitxml

I'm using Laravel and this is my ./phpunit.xml file

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="FeatureTests">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="UnitTests">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="DB_CONNECTION" value="sqlite_testing" />
    </php>
</phpunit>

I'm firing one of my test suites with the following command:

./vendor/phpunit/phpunit/phpunit --testsuite UnitTests

Inside my test method I have:

public function testAllMandatoryData()
{
   dump(env('APP_ENV'));
   ....
}

It's displaying "local" I was expecting "testing" as specified in phpunit.xml

         <env name="APP_ENV" value="testing"/>

Edit: additional details
I have this laravel application running in a Docker container

On the docker-compose.yml I set some environment variables like:

environment:
  - APP_ENV=local
  - DB_HOST=192.168.0.22
  - DB_PORT=33306
  - DB_DATABASE=mydatabase
  - DB_USERNAME=homestead
  - DB_PASSWORD=homestead

What I've noticed is that directives in phpunit.xml like:

    <env name="APP_ENV" value="testing"/>

have no effect when the name is there in the docker-compose already.

Instead if I add some not defined in docker-compose.yml will be correctly set at phpunit runtime, like:

    <env name="DB_CONNECTION" value="sqlite_test"/>

end Edit

What I'm missing?

Thanks

Best Answer

use

<env name="APP_ENV" value="testing" force="true"/>
<env name="CACHE_DRIVER" value="array" force="true"/>
<env name="SESSION_DRIVER" value="array" force="true"/>
<env name="QUEUE_DRIVER" value="sync" force="true"/>
<env name="DB_CONNECTION" value="sqlite_testing" force="true"/>

Without the force parameter, it won't work. See this issue: https://github.com/sebastianbergmann/phpunit/issues/2353 and the merged PR: https://github.com/sebastianbergmann/phpunit/pull/2723

Related Topic