我有一个“配置”类,它有一个方法“getConfig”,它读取配置文件“config.ini”,其中包含所有应用程序配置(数据库凭据和主机,一些apis键,.....)
现在我有这个单元测试,用于测试配置文件中是否存在数据库条目,同时确认方法“getConfig”返回的数组具有密钥“database”:
function testConfigFileHasDatabaseEntry()
{
$configuration = Configuration::getInstance();
$arrConfig = $configuration->getConfig();
$this->assertArrayHasKey('database', $arrConfig);
}
我还有另一个单元测试,它确认“getConfig”返回一个类型为array的变量。
我的问题如下: 就单元测试最佳实践而言,在这种情况下,此测试足以确认函数getConfig已经过充分测试,或者最好确认配置文件中是否存在每个密钥。我认为确认所有条目都在配置文件中可能属于另一类测试,但我想确定。
让我知道在这种情况下最佳做法是什么。
根据gcontrollez的回答,我意识到发布类源代码更好:
<?php
/**
* Loads the configuration file
*/
namespace Example\Lib;
class Configuration {
private static $instance;
private $arrConfig;
/**
* Constructor: loads the config file into property arrConfig and dies if unable
* to load config file
*
* @return void
*/
private function __construct()
{
$this->arrConfig = parse_ini_file("config/settings.ini", true);
if ($this->arrConfig == false){
die("Cannot load configuration file");
}
}
/**
* returns an instance of this singleton class
*
* @return Configuration
*/
public static function getInstance()
{
if (self::$instance == null){
self::$instance = new Configuration();
}
return self::$instance;
}
/**
* Getter for the property arrConfig
*
* @return array:
*/
public function getConfig() {
return $this->arrConfig;
}
}
由于
答案 0 :(得分:0)
You are not unit testing the getConfig
method. You are just checking that its result contains certain data. This is perfectly valid and can be useful but is not a unit test.
If you wanted to unit test the getConfig
method, you should check it's behaviour with each possible config.ini
file. I suppose you are using the parse_ini_file
function inside getConfig
. So in order to unit test the getConfig
method you should check all the possible cases you think that can happen:
- testConfigFileIsLoaded
- testExceptionThrownIfConfigFileFailsToLoad
The parse_ini_file
returns an array or false so those are the cases that you should check.
For that you need to be able to change the .ini
file to be used. If it's harcoded inside the Configuration
class you wont be able to do that.