Search code examples
phplaravelphpunitlaravel-artisanmockery

Mocking Laravel configuration cache


I am writing a new artisan command which I do not want to run if the configuration is cached (via config:cache):

class NewCommand extends Command
{
    public function handle()
    {
        if (app()->configurationIsCached())
        {
            $this->error('Configuration is cached.  Unable to run command');
            return 1;
        }
    }
}

I am trying to write a Unit test to cover this, however this fails:

public function test_command_not_run_if_config_cached()
{
    App::shouldReceive('configurationIsCached')
        ->once()
        ->andReturn(true);

    $this->artisan('new:command')
        ->expectsOutput('Configuration is cached.  Unable to run command');
        ->assertExitCode(1);
}

result: Method configurationIsCached() from Mockery_0_Illuminate_Foundation_Application should be called exactly 1 times but called 0 times

Is there another way to mock that the configuration is cached in the unit test?


Solution

  • Turns out that configurationIsCached() is available on the App facade. This is not currently documented, but updating the handle function in the command to

    public function handle()
    {
        if (App::configurationIsCached())
        {
            $this->error('Configuration is cached.  Unable to run command');
            return 1;
        }
    }
    

    allows the test to pass. Thanks to @Namosheck for pointing this out