【问题标题】:PHP - How can I test this class?PHP - 我如何测试这个类?
【发布时间】:2020-02-06 23:19:18
【问题描述】:

我刚刚开始使用 PHPUnit,我正在努力研究如何测试某些功能。例如,我有以下加载 DotEnv 库的类,我想测试以下功能...

  1. 测试变量是否加载
  2. 如果配置已缓存,则不测试
  3. 如果缺少必需的变量,测试它会引发异常

但我正在努力寻找最好的方法来做到这一点$app->configurationIsCached() 在其他地方进行管理,因此阻止了其他班级的执行。

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

【问题讨论】:

  • 由于您的类实际上不允许任何东西(派生类除外)查看加载的值,因此您可能必须派生一个测试类以允许您检查加载的内容。但至于其余部分,您可以模拟 Core 类并确保使用 configurationIsCached() 调用它,至于所需 - 创建一个缺少一些值的测试 .env 文件并检查是否引发异常。如果没有这些类的代码,就很难编写和测试某些东西以确保它反映您正在使用的实际代码。
  • 我建议vfsStream模拟文件系统

标签: php unit-testing testing phpunit


【解决方案1】:

关于你的代码被$app-&gt;configurationIsCached():

使用 Mockery 之类的东西创建一个模拟 Core 类,您将作为 $app 传递给您的类。然后,您可以模拟 configurationIsCached(),让它返回将您的课程路由到提前返回或调用您的 load() 方法所需的任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2020-02-10
    • 2013-02-24
    • 1970-01-01
    • 2015-10-31
    • 2011-04-12
    相关资源
    最近更新 更多