1

I'm working on a package that relies on the Config facade. The code itself works fine, but I'm encountering issues when testing.

Initially, I was using this code:

Config::shouldReceive('foo.bar')
    ->andReturn(true);

As many others, I bumped into some issues.

I later read that mocking the Config facade isn't encouraged.

To get around it, most people tend to suggest to use the following instead:

Config::set('foo.bar', true);

Which I reckon works fine, if you're testing from Laravel/Lumen.

But my issue is, I'm not. I just rely on a few Illuminate packages, so that won't work since I get: RuntimeException: A facade root has not been set.

At this point, some might suggest that I should just inject the Config repository dependency, but I'm using the Config facade in a trait which is used by an Eloquent model, so DI won't work.

Is there any other way I can tackle this?

Thanks!

PS: This question has also been posted on Laracasts

Quetzy Garcia
  • 1,820
  • 1
  • 21
  • 23

2 Answers2

1

I faced to the same issue. Lumen 5.4 using Config::set('key', 'value') was not worked. So I had to use this way.

//test
use Illuminate\Support\Facades\Config;

Config::shouldReceive('get')
                    ->once()
                    ->with('key')
                    ->andReturn('value');

,

//code
use Illuminate\Support\Facades\Config;

Config::get('key'); //instead config('key');
  • Your issue isn't related to mine. You're using Lumen, which still has most of the `Illuminate` packages, so the `Config::set()` should work as long as you enable Facades in the `bootstrap/app.php`. My use case is for testing a Laravel/Lumen package in a standalone environment, where you don't have an entire framework at your disposal, so you have to rely on Testbench. Also, as stated in the documentation, mocking the `Config` isn't a best practice. Hence, the downvote. – Quetzy Garcia Jul 19 '17 at 11:56
0

For those running into a similar issue, I've finally found the correct way to address this problem.

Testing Laravel packages is just what the Testbench package is for.

From the documentation:

To use Testbench Component, all you need to do is extend Orchestra\Testbench\TestCase instead of PHPUnit\Framework\TestCase.

This way, setting a configuration value is just a matter of calling Config::set() as you would on a full Laravel install. No more Mockery issues.

Quetzy Garcia
  • 1,820
  • 1
  • 21
  • 23