我无法正确测试抛出的异常(这是一个namspacing问题)。
这是我的自定义例外:
<?php
namespace Example\Customexception;
class ResourceNotAvailableException extends \Exception {}
这是我正在测试的课程:
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;
}
}
这是我的测试课:
use Example\Lib\Configuration;
class ConfigurationTest extends PHPUnit_Framework_TestCase {
/**
* @expectedException Example\Customexception\ResourceNotAvailableException
*/
function testGetInstanceThrowsException()
{
$configuration = Configuration::getInstance("configtestini");
}
}
这是我得到的输出:
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.
请忽略输出中的行号,因为我从代码中删除了一些注释,以便在此处轻松阅读。
由于
答案 0 :(得分:0)
parse_ini_file()
引发错误,该错误由PHPUnit的错误处理程序转换为异常。