samedi 30 avril 2016

PHPUnit fails testing a custom exception

I am having trouble to test correctly a thrown exception (Is it a namspacing problem).

Here is my custom exception:

<?php
namespace Example\Customexception;

class ResourceNotAvailableException extends \Exception {}

Here the class I am testing:

namespace Example\Lib;

use Example\Customexception\ResourceNotAvailableException;

class Configuration {

    private static $instance;

    private $arrConfig;

    private function __construct($configFile)
    {
        $this->arrConfig = parse_ini_file($configFile, true);
        if ($this->arrConfig == false){
            throw new ResourceNotAvailableException("Config file {$configFile} not available.");
        }   
    }

    public static function getInstance($configFile = "config/config.ini")
    {
        if (self::$instance == null){
            try {
                self::$instance = new Configuration($configFile);
            }
            catch(ResourceNotAvailableException $e) {
                throw $e;
            }
        }
        return self::$instance;
    }

}

And here is my test class:

use Example\Lib\Configuration;

class ConfigurationTest extends PHPUnit_Framework_TestCase {


    /**
     * @expectedException Example\Customexception\ResourceNotAvailableException
     */ 
    function testGetInstanceThrowsException()
    {
        $configuration = Configuration::getInstance("configtestini");       
    }


}

And here is the output I get:

PHPUnit 5.3.2 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 89 ms, Memory: 2.75Mb

There was 1 error:

1) ConfigurationTest::testGetInstanceThrowsException
parse_ini_file(configtestini): failed to open stream: No such file or directory

/home/me/workspace/codeexample/src/Lib/Configuration.php:24
/home/me/workspace/codeexample/src/Lib/Configuration.php:39
/home/me/workspace/codeexample/tests/unit/Lib/ConfigurationTest.php:14

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

Please ignore the line numbers in the output because I removed some comments from the code to make it easily readable here.

Thanks

Aucun commentaire:

Enregistrer un commentaire