gpt4 book ai didi

PHP - 我如何测试这个类?

转载 作者:行者123 更新时间:2023-11-28 21:15:58 24 4
gpt4 key购买 nike

我刚刚开始使用 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);
}
}

最佳答案

关于您的代码被 $app->configurationIsCached() 捆绑:

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

关于PHP - 我如何测试这个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58307206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com