themosis / framework

The Themosis framework core.
https://framework.themosis.com/
GNU General Public License v2.0
671 stars 121 forks source link

Test (phpunit) has no access to config #873

Closed ligne13 closed 2 years ago

ligne13 commented 2 years ago

I created a Test in the tests directory. I need to access config variables within this Test. But when running phpunit I get this error :

1) App\Tests\MailChimpAPITest::testAPIConnexion ReflectionException: Class config does not exist

The code :

<?php

namespace App\Tests;

use MailchimpMarketing\ApiClient;
use PHPUnit\Framework\TestCase;

class MailChimpAPITest extends TestCase
{
    public function testAPIConnexion()
    {
        $mailchimp = new ApiClient();

        $config = [
            'apiKey' => config('app.mailchimp_api_key'),
            'server' => config('app.mailchimp_api_server_prefix'),
        ];
        $this->assertIsString($config['apiKey']);
        $this->assertIsString($config['server']);

        $mailchimp->setConfig($config);
    }
}

Thanks

jlambe commented 2 years ago

Currently, when running tests, the framework is not bootstrapped as expected. What you have is a very bare-bone implementation of PHPUnit. Using the config() function as is will call the service container and try to load the config repository class that is not yet registered.

If you need the config repository, you first need to get the application service container and then bind the config repository class to it in order to use it.

But if I can give a suggestion, based on your code snippet, I won't test that API Client class provided by a third-party package. If you need the results of a call to the external resource, I would mock the expected results and use that to test your code.

ligne13 commented 2 years ago

I managed to use config in my tests by adding this single line at the end of /tests/bootstrap.php :

require DIR.'/../htdocs/cms/wp-load.php';

jlambe commented 2 years ago

Yes, this also loads everything but I think it might only works if WordPress is installed. From a CI/CD perspective you might get issues perhaps.