PHPUnit : How to force an environment variable in Unit Test ?

In Magento 2 we all follow TDD approach and we often have a requirement to use the constants and global variables.

<Magento Directory>/dev/tests/unit/phpunit.xml

The element and its children can be used to configure PHP settings, constants, and global variables.

<php>
    <ini name="date.timezone" value="America/Los_Angeles"/>
    <ini name="xdebug.max_nesting_level" value="200"/>
    <ini name="memory_limit" value="-1"/>
    <env name="BASE_URL" value="http://127.0.0.1/V1/rest/" force="true" />
</php>

If you running individual Unit Case then you need to set the configuration path. I always run them from within PHPStorm. And there is an option to define the phpunit.xml path. Preferences > Languages & Frameworks > PHP > Test Frameworks

Configuring PHPUnit

Call the global variable in your setUp() function of the Unit Test.

 protected function setUp()
 {
    $baseUrl = $_ENV['BASE_URL'];
 }

Leave a Reply

Your email address will not be published. Required fields are marked *