【发布时间】:2020-02-06 23:19:18
【问题描述】:
我刚刚开始使用 PHPUnit,我正在努力研究如何测试某些功能。例如,我有以下加载 DotEnv 库的类,我想测试以下功能...
- 测试变量是否加载
- 如果配置已缓存,则不测试
- 如果缺少必需的变量,测试它会引发异常
但我正在努力寻找最好的方法来做到这一点$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