Laravel phpunit not getting right url

2020-04-06 00:09发布

问题:

I've changed the app.url config value to the correct url (http://testing.local) for testing locally, however when I run my phpunit tests and try to call(), it is trying to query http://localhost instead of the value of app.url. What do I need to do to get phpunit to call the right path?

I know that it is not actually calling the url, just processing it as if it was, but I can't seem to get it to actually work. Could it have something to do with testing.local directly linking to /public instead of /?

回答1:

To change testing url of PHPUnit:

Go to /tests/TestCase.php in your Laravel project.

Change next line to url you need:

// The base URL to use while testing the application.
protected $baseUrl = 'http://newurl.com';

Done.



回答2:

If you want to statically specify a root URL for your tests, add this to phpunit.xml:

<env name="APP_URL" value="http://testing.local"/>

Instead, if you want to change the URL dinamically during your tests, from Laravel 5.4 the $baseUrl method doesn't work anymore

Also, trying to set the url dinamically with \Config:set('app.url', 'http://testing.local') doesn't work either, as it seems that Laravel caches the root url

You can set dynamically a custom URL with:

\URL::forceRootUrl('http://testing.local');


回答3:

As stated above, you can use Config::get('app.url') anywhere in your laravel code, including your unit-test.

Note: it is recommended to set this value in your .env file so that it can be set specifically for each environment.

When working with config and .env variables, remember to clear the cache for these with the following commands:

php artisan cache:clear
php artisan config:cache


回答4:

To the best of my understanding, Laravel is supposed to use the 'testing' environment variables when you run PHPUnit. However, I am having the same issue that you are. To get it to work I manually set the app url.

$test_url = Config::get('app.url');

Hope this helps anyone who comes across the same issue.



回答5:

I think the best way is to set the test app url in phpunit.xml configuration file:

<env name="APP_URL" value="some-url.test"/>