I'm making an automatic email sending program in laravel and I need to test it with different email providers. I'm doing the tests with PHPUnit and I wanted to know if there is any way to change the variables of the .env file such as 'mail_host' for example directly in the test.
I tried to use the following code to change but it didn't work:
config([
'MAIL_HOST' => ' smtp.mail.yahoo.com'
]);
I'm using laravel version 8.79 and PHP 7.4
CodePudding user response:
You can change any .env variable during tests in Laravel from the phpunit.xml file.
Here is an example of my XML:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit>
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./app</directory>
</include>
</coverage>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<PHP>
<!-- Here you can change any PHP env -->
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="MAIL_DRIVER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="DB_CONNECTION" value="testing"/>
</php>
</phpunit>
CodePudding user response:
you can change directly int the .env file MAIL_HOST variable. If you are testing I recommend to set up a mailtrap account, which is ideal for testing see more information https://mailtrap.io https://www.itsolutionstuff.com/post/laravel-send-mail-using-mailtrap-exampleexample.html
CodePudding user response:
If you need to dynamically change an env variable, you can change it using $_ENV['variable'], but you should never do so using that.
To solve that issue, you have to use the config helper, as you did, but instead of using the environment variable as a key, use the real config path.
For example, if you have this config file (config/testing.php) like this:
<?php
return [
'mail' => [
'host' => env('TESTING_MAIL_HOST', 'fake.host.com'),
],
];
You can do config(['testing.mail.host' => 'new.domain.com']); inside your test before you run the code you want to test, so when you use config('testing.mail.host'); in the real code, you will get new.domain.com value back instead of fake.host.com or whatever you were using for TESTING_MAIL_HOST.
Remember that this is an example, TESTING_MAIL_HOST does not exist.
