phpunit - Unit testing of a class reading a configuration file -
i have class "configuration" has method "getconfig" reads configuration file "config.ini" have app configs (database credentials , host, apis keys, .....)
for have unit test tests if database entry exists in config file , @ same time confirms array returned method "getconfig" has key "database":
function testconfigfilehasdatabaseentry() { $configuration = configuration::getinstance(); $arrconfig = $configuration->getconfig(); $this->assertarrayhaskey('database', $arrconfig); }
i have unit test confirms "getconfig" returns variable of type array.
my question following: in terms of unit testing best practices, in case test enough confirm function getconfig tested or better confirm every key exists in config file. think confirming entries in config file maybe falls under category of testing, want sure.
let me know best practice in case.
base on answer of gcontrollez realized better post class source code:
<?php /** * loads configuration file */ namespace example\lib; class configuration { private static $instance; private $arrconfig; /** * constructor: loads config file property arrconfig , dies if unable * 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 instance of singleton class * * @return configuration */ public static function getinstance() { if (self::$instance == null){ self::$instance = new configuration(); } return self::$instance; } /** * getter property arrconfig * * @return array: */ public function getconfig() { return $this->arrconfig; } }
thanks
you not unit testing getconfig
method. checking result contains data. valid , can useful not unit test.
if wanted unit test getconfig
method, should check it's behaviour each possible config.ini
file. suppose using parse_ini_file
function inside getconfig
. in order unit test getconfig
method should check possible cases think can happen:
- testconfigfileisloaded - testexceptionthrownifconfigfilefailstoload
the parse_ini_file
returns array or false cases should check.
for need able change .ini
file used. if it's harcoded inside configuration
class wont able that.
Comments
Post a Comment