Issues Mocking basePath Method in Laravel Tests
I'm trying to mock the basePath method in my Laravel application to test some functionality. My main code uses the base_path helper function like this:
$modules = $this->getModules(base_path('modules'));
In my test, I'm attempting to mock this helper function. Here is the code I've used in my test:
$testModulesPath = '/path/to/test/modules';
$pathMock = $this->partialMock(\Illuminate\Foundation\Application::class, function ($mock) use ($testModulesPath) {
$mock->shouldReceive('basePath')->andReturn($testModulesPath);
});
dd(
'test mock',
app(\Illuminate\Foundation\Application::class)->basePath(),
app()->basePath()
);
The output from dd is:
"test mock"
"/path/to/test/modules"
"/var/www/html"
It seems like app(\Illuminate\Foundation\Application::class)->basePath() returns the mocked path correctly, but app()->basePath() still returns the original path and base_path helper function use it.
What I've Tried: Partially mocking \Illuminate\Foundation\Application class. Binding the mock instance to the container using $this->app->instance(...). Alias \Illuminate\Foundation\Application::class to 'app'.
The base_path helper function does not seem to use the mocked basePath method.
Please or to participate in this conversation.