简体   繁体   中英

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);
    }
}

Regarding your code getting tied up on the $app->configurationIsCached() :

Use something like Mockery to create a mock of your Core class you're passing in as $app to your class. You can then mock configurationIsCached() , having it return whatever is needed to route your class through to the early return or the call to your load() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM