request()->url() and request()->segments() are not available while service providers are under register/boot state, but this happens only in phpunit environment. In normal laravel app environment this variables are fully available in this states. Also when testing with dusk, variables are available, problem is just in phpunit.
routes/web.php
Route::get('/one/two', function () {
return "\n".request()->url();
});
AppServiceProvider.php
public function boot()
{
echo request()->url();
}
tests/Feature/ExampleTest.php
public function testBasicTest()
{
$response = $this->call('GET', '/one/two');
dd($response->getContent());
}
This is also normal behavior in basic laravel app while testing in browser. First AppServiceProvider returns echo with correct url, and then route returns second time same correct url.

First AppServiceProvider returns wrong url path, but route returns correct url.

I found same issue from 2017th, but I could not find answer for this issue.
https://github.com/laravel/framework/issues/18678
Thank your for reply,
have a nice day.
I have to admit that I'm not sure why the behavior is different. I think it's because you're operating in a CLI context for the unit test and the request isn't bootstrapped for that context. But not entirely sure. I'll leave this open for a bit to see if someone else can provide some other insights.
Same problem here
If you look in the vendor\symfony\http-foundation\Request.php there is no path in the array when the url is parsed with parse_url.
is there any news about this issue?
I think it's because you're operating in a CLI context for the unit test and the request isn't bootstrapped for that context.
@driesvints has given the complete answer on this, Matter of fact in PHPUnit a request object is only generated after the app is has booted and when the test actually called call(), post(), get(), put(), delete() to generate a request.
Can this be fixed? Not possible in PHPUnit because you need to prepare the request before booting the app, but you need the booted app to prepare the tests such as running migration etc.
This also is why you don't have this issue with Laravel Dusk.
Thanks for the explanation @crynobone. It doesn't seems that we can fix this but if anyone wants to give it a go feel free to send in a PR.
Most helpful comment
Same problem here
If you look in the
vendor\symfony\http-foundation\Request.phpthere is nopathin the array when the url is parsed withparse_url.