themosis / framework

The Themosis framework core.

Home Page:https://framework.themosis.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Test (phpunit) has no access to config

ligne13 opened this issue · comments

  • Themosis Version: 2.1.0
  • WordPress Version: 6.0.2
  • PHP Version: 7.4

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

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.

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';

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.