uccdev's avatar

Can't get config value in test case?

Hi, In one of my test cases, I'm trying to fetch a config value:

    <?php

    namespace Tests\Feature;
    
    use Tests\TestCase;
    use Illuminate\Foundation\Testing\WithFaker;
    use Illuminate\Foundation\Testing\RefreshDatabase;
    use Illuminate\Support\Facades\Facade;
    use App\Http\Controllers\CourseController;
    use App\Config\Values;

    class CurlTest extends TestCase
    {
        protected $token;

        public function __construct() {
          $this->token = config('values.accessToken');
        }
        public function testExample() {
          //some test function
        }
        ...
    }

However, I believe the __construct is giving me an error: Fatal Error: Uncaught ReflectionException: Class config does not exist in C:\directoryPath\Illuminate\Container.php:779

This isn't an error I have in any of my working code that makes this config call, just in this one test case. Can anyone explain to me why this isn't working, and what might instead?

0 likes
3 replies
Nakov's avatar
Nakov
Best Answer
Level 73

You should be using the setUp method of the TestCase which will run before each test, something like this:

protected $token;

protected function setUp(): void
{
    parent::setUp();

    $this->token = config('values.accessToken');

}
1 like
uccdev's avatar

I see, thank you for enlightening me. That did the trick!

tafhyseni's avatar

And if anyone needs the same for PEST. It can be achieved using beforeAll() or beforeEach().

// this will run before all tests in the file. If you need to run this before each test.. then use beforeEach
beforeAll(function () {
    $this->token = config('values.accessToken');
});
1 like

Please or to participate in this conversation.