我刚刚开始使用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);
}
}
答案 0 :(得分:1)
关于您的代码与$app->configurationIsCached()
捆绑在一起:
使用类似Mockery的东西来创建您要Core
的类的模拟,您以$app
的形式传递给您的类。然后,您可以模拟configurationIsCached()
,让它返回将类路由到早期返回或调用load()
方法所需的一切。