Pat*_*ick 11 php phpunit unit-testing namespaces symfony
我在5.3中使用命名空间并尝试使用Symfony2框架在PHPUnit中测试预期的异常.
我期待抛出一个异常,当我使用它时
$this->setExpectedException('ImageResizerException');
我收到以下错误:
Sebastian Bergmann的PHPUnit 3.7.13.
配置从/var/www/branches/3.6.0/api/app/phpunit.xml.dist中读取
.E .................
时间:1秒,记忆:18.25Mb
有1个错误:
1)AssetManagerBundle\Tests\Services\ImageResizerTest :: testOriginalFile ReflectionException:类ImageResizerException不存在
FAILURES!测试:19,断言:54,错误:1.
我有以下结构:
我的考试班:
<?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....
}
Run Code Online (Sandbox Code Playgroud)
我是否必须为PHPUnit做一些特殊的事情来查看我的异常类?
PHP版本:
带有Suhosin-Patch的PHP 5.3.10-1ubuntu3.5(cli)(内置:2013年1月18日23:45:59)版权所有(c)1997-2012 PHP Group Zend Engine v2.3.0,版权所有(c)1998-2012 Zend Technologies与Xdebug v2.1.0,版权所有(c)2002-2010,作者:Derick Rethans
Rez*_*a S 28
您需要完全限定异常类及其名称空间.例如:
$this->setExpectedException('\AssetManagerBundle\Services\Exceptions\ImageResizerException');
Run Code Online (Sandbox Code Playgroud)
要么
use AssetManagerBundle\Services\Exceptions\ImageResizerException;
$exceptionClass = get_class(new ImageResizerException(''));
$this->setExpectedException($exceptionClass);
Run Code Online (Sandbox Code Playgroud)
您需要使用FQCN中的ImageResizerException
异常:
AssetManagerBundle\Services\Exceptions\ImageResizerException
Run Code Online (Sandbox Code Playgroud)
该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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8391 次 |
最近记录: |