我在5.3中使用命名空间,并尝试使用Symfony2框架测试PHPUnit中的预期异常。
我期待抛出异常,当我使用
$this->setExpectedException('ImageResizerException');
我收到以下错误:
PHPUnit 3.7.13 Sebastian Bergmann。
从中读取的配置 /var/www/branches/3.6.0/api/app/phpunit.xml.dist
.e......
时间: 1 秒, 内存: 18.25Mb
有 1 个错误:
1) AssetManagerBundle''Tests''Services''ImageResizerTest::testOriginalFile 反射异常:类图像调整器异常不存在
失败!测试: 19, 断言: 54, 错误: 1.
我有以下结构:
- AssetManagerBundle''Services''ImageResizer.php
- AssetManagerBundle''Services''Exceptions''ImageResizerException.php
- AssetManagerBundle''Tests''Services''ImageResizerTest.php
我的测试类:
<?php
namespace AssetManagerBundle'Tests'Services;
use AssetManagerBundle'Services'ImageResizer;
use AssetManagerBundle'Services'Exceptions'ImageResizerException;
class ImageResizerTest extends 'PHPUnit_Framework_TestCase
{
public function testOriginalFile()
{
$ir = new ImageResizer();
// test default value
$this->assertEquals('', $ir->getOriginalFile());
// test invalid filename
$this->setExpectedException('ImageResizerException');
$ir->setOriginalFile('/tmp/test.file');
$this->assertEquals('/tmp/test.file', $ir->getOriginalFile());
// test valid filename
$temp_name = tempnam(sys_get_temp_dir(), 'test_'.time());
$handle = fopen($temp_name, 'w+');
fwrite($handle, ' ');
fclose($handle);
$ir->setOriginalFile($temp_name);
$this->assertEquals($temp_name, $ir->getOriginalFile());
}
// more code....
}
我是否必须做一些特别的事情才能让 PHPUnit 看到我的异常类?
PHP版本:
PHP 5.3.10-1ubuntu3.5 与 Suhosin-Patch (cli) (构建时间: Jan 18 2013 23:45:59) 版权所有 (c) 1997-2012 PHP 组 Zend 引擎 v2.3.0, 版权所有 (c) 1998-2012 Zend Technologies 与 Xdebug v2.1.0, 版权所有 (c) 2002-2010, 作者:Derick Rethans
您需要完全限定异常类及其命名空间。例如:
$this->setExpectedException(''AssetManagerBundle'Services'Exceptions'ImageResizerException');
或
use AssetManagerBundle'Services'Exceptions'ImageResizerException;
$exceptionClass = get_class(new ImageResizerException(''));
$this->setExpectedException($exceptionClass);
使用ImageResizerException
异常的 FQCN:
AssetManagerBundle'Services'Exceptions'ImageResizerException
文件顶部的 use
子句仅适用于该文件 - 不适用于在其他一些文件中具有其代码的 PHPUnit。
更正:不仅)use
子句不适用于 PHPUnit,而是因为该ReflectionClass
需要 FQCN。在PHP中使用变量(动态)类名时,这类似new $var
:
<?php
namespace Sugar {
class Exception extends 'Exception {}
}
namespace {
use Sugar'Exception;
$class = 'Sugar'Exception';
$e = new $class;
var_dump($e);
}
输出:
object(Sugar'Exception)#1 (7) {
["message":protected]=>
string(0) ""
["string":"Exception":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(45) "/tmp/execpad-7141d0116de7/source-7141d0116de7"
["line":protected]=>
int(10)
["trace":"Exception":private]=>
array(0) {
}
["previous":"Exception":private]=>
NULL
}
演示:http://eval.in/7883
不要编写类名,而是改用类的完整命名空间。然后,您将不会获得"类不存在"异常。
$this->setExpectedException(ImageResizerException::class);
是使用从 use
语句导入的命名空间执行此操作的方法
我遇到了类似的问题,但是对于phpunit,在声明@expectedException的同时,它还需要FQCN。
/**
* @expectedException 'PHPNS'Core'MyCustomException
*/
public function testIfListIsEmpty()
{
$fab = new PHPList();
}
希望对某人有所帮助。