我发现PHPUnit的注释@expectedException不希望从use语句中读取类命名空间路径(我使用psr-0进行自动加载)。
以这为例:
<?php
namespace Outrace\Battleship\Tests;
use Outrace\Battleship\Collection\MastCollection;
use Outrace\Battleship\Exception\CollectionOverflowException;
class MastCollectionTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException CollectionOverflowException
*/
public function testAcceptOnlyMasts()
{
$notMastObject = new \stdClass();
$mastCollection = new MastCollection();
$mastCollection->attach($notMastObject);
}
}当运行该测试时,将导致以下错误:
ReflectionException:类CollectionOverflowException不存在
为了纠正这种情况,我再次尝试将autoload-dev添加到我的compose.json中并转储autoload文件:
"autoload-dev": {
"classmap": [
"src/Outrace/Battleship/Exception/"
]
},或者是psr-4:
"autoload-dev": {
"psr-4": {
"Outrace\\Battleship\\Tests\\": "src/Outrace/Battleship/Tests/",
"Outrace\\Battleship\\Exception\\": "src/Outrace/Battleship/Exception/"
}
},以上任何一项都无法解决问题,错误将持续存在。
但是,如果注释引用异常类的富勒限定名,则测试将运行良好:
/**
* @expectedException Outrace\Battleship\Exception\CollectionOverflowException
*/
public function testAcceptOnlyMasts()这是PHPUnit的限制,还是我做错了什么?
发布于 2016-03-18 10:08:04
这是phpunit工作方式的一个限制。
在内部,它使用php的ReflectionClass,它期望异常的FQCN。它只需要你在注释中给它的字符串。
TestCase.php在检查异常时,$reflector = new ReflectionClass($this->expectedException);和expectedException属性都是从注释或对setExpectedException()的调用中填充的。
如果使用setExpectedException()方法,则可以使用简化的名称,然后可以执行以下操作
<?php
namespace Outrace\Battleship\Tests;
use Outrace\Battleship\Collection\MastCollection;
use Outrace\Battleship\Exception\CollectionOverflowException;
class MastCollectionTest extends \PHPUnit_Framework_TestCase
{
public function testAcceptOnlyMasts()
{
$this->setExpectedException(CollectionOverflowException::class);
$notMastObject = new \stdClass();
$mastCollection = new MastCollection();
$mastCollection->attach($notMastObject);
}
}https://stackoverflow.com/questions/36081107
复制相似问题