问题描述
我正在5.3中使用命名空间,并尝试使用Symfony2框架在PHPUnit中测试预期的异常.
I am using namespacing in 5.3 and trying to test for an expected exception in PHPUnit with the Symfony2 framework.
我期望在使用
$this->setExpectedException('ImageResizerException');
我收到以下错误:
从中读取配置 /var/www/branches/3.6.0/api/app/phpunit.xml.dist
Configuration read from /var/www/branches/3.6.0/api/app/phpunit.xml.dist
.E ........
.E.................
时间:1秒,内存:18.25Mb
Time: 1 second, Memory: 18.25Mb
有1个错误:
1) AssetManagerBundle \ Tests \ Services \ ImageResizerTest :: testOriginalFile ReflectionException:类ImageResizerException不存在
1) AssetManagerBundle\Tests\Services\ImageResizerTest::testOriginalFile ReflectionException: Class ImageResizerException does not exist
失败!测试:19,断言:54,错误:1.
FAILURES! Tests: 19, Assertions: 54, Errors: 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做一些特殊的事情才能看到我的异常类吗?
Do I have to do something special for PHPUnit to see my exception class?
PHP版本:
推荐答案
您需要完全限定异常类及其名称空间.例如:
You need to fully qualify the exception class along with its namespace. For ex:
$this->setExpectedException('\AssetManagerBundle\Services\Exceptions\ImageResizerException');
或
use AssetManagerBundle\Services\Exceptions\ImageResizerException;
$exceptionClass = get_class(new ImageResizerException(''));
$this->setExpectedException($exceptionClass);
这篇关于PHPUnit找不到异常类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!