mercredi 9 octobre 2019

PHP - How can I test this class?

I'm just getting started with PHPUnit and I'm struggling on how to test certain features. For example, I've got the following class with loads the DotEnv library, and I'd like to test the following features...

  1. Test the variables are loaded
  2. Test it doesn't if the config is already cached
  3. Test it throws an exception if a required variable is missing

But I'm struggling with the best way to do this $app->configurationIsCached() is managed elsewhere so blocks then rest of the class from executing.

<?php declare(strict_types=1);

namespace Foundation\Bootstrap;

use Dotenv\Dotenv;
use Foundation\Core;

class LoadEnvironmentVariables
{


    /**
     * Any required variables.
     *
     * @var array
     */
    protected $required = [
        'APP_URL',
        'DB_NAME',
        'DB_USER',
        'DB_PASS',
        'DB_HOST'
    ];


    /**
     * Creates a new instance.
     *
     * @param Core $app The application instance.
     */
    public function __construct(Core $app)
    {

        // If the configuration is cached, then we don't need DotEnv.
        if ($app->configurationIsCached()) {
            return;
        }

        // Load the DotEnv instance
        $this->load($app->get('paths.base'));
    }


    /**
     * Loads the .env file at the given path
     *
     * @param string $filePath The path to the .env file
     * @return void
     */
    public function load(string $filePath)
    {
        $dotEnv = Dotenv::create($filePath);
        $dotEnv->safeLoad();
        $dotEnv->required($this->required);
    }
}

Aucun commentaire:

Enregistrer un commentaire