【发布时间】:2023-03-13 16:16:01
【问题描述】:
我想使用已在类中的 config.php 文件中声明的变量进行测试。我不确定这是否像我所做的那样是正确的。
我有一个配置文件,config.php:
class Config {
public $hosts = array(
'a' => '192.168.1.10'
'b' => '192.168.1.11',
);
public $ports = array(
'a' => 22,
'b' => 22,
);
}
我想将这个变量包含在一个名为 Tests.php 的文件中:
require_once 'config.php';
class Test extends PHPUnit_Framework_TestCase
{
protected $hosts;
protected $ports;
public function __construct()
{
$config = new Config();
$this->hosts = $config->hosts;
$this->portsSsh = $config->ports;
}
public function testConnect()
{
$session = $this->connect($this->hosts['a'], $this->ports['a']);
$this->closeConnection($session);
}
...
}
这样做对吗? 我的印象是太复杂了。我必须为 config.php 文件创建一个类,并且在测试类中我必须像映射 $this->hosts = $config->hosts 一样。
没有更简单的方法吗?我不想使用全局变量。
【问题讨论】:
-
为什么不是使用 parse_ini_file PHP 函数解析的真实配置文件 (config.ini)?
-
就其本身而言,这里唯一直接的问题是您的
Config相关代码应该在setUp方法中,而不是在构造函数中。但更让我担心的是您编写Config课程的方式。在 PHP 中硬编码您的配置被认为是相当不安全的,并且会使您的代码难以在大型项目中使用。请考虑发布您的一些代码on codereview 以获取有关此问题的更多详细信息,以及有关如何更好地解决该问题的一些建议 -
@Elias Van Ootegem:感谢您的回答和推荐。我做到了。