顺便提一下,我正在使用 SimpleTest 1.1alpha。
我有一个单例类,并且我想编写一个单元测试来保证这个类是一个单例类,方法是尝试实例化该类(它有一个私有构造函数)。
显然,这会导致致命错误:
Fatal error: Call to private FrontController::__construct()
是否有任何方法可以"捕获"这个致命错误并报告通过的测试?
顺便提一下,我正在使用 SimpleTest 1.1alpha。
我有一个单例类,并且我想编写一个单元测试来保证这个类是一个单例类,方法是尝试实例化该类(它有一个私有构造函数)。
显然,这会导致致命错误:
Fatal error: Call to private FrontController::__construct()
是否有任何方法可以"捕获"这个致命错误并报告通过的测试?
致命错误会停止脚本的执行。
而且没有必要以那种方式测试单例。如果您坚持检查构造函数是否为私有的,可以使用ReflectionClass:getConstructor()。
public function testCannotInstantiateExternally()
{
$reflection = new \ReflectionClass('\My\Namespace\MyClassName');
$constructor = $reflection->getConstructor();
$this->assertFalse($constructor->isPublic());
}
另一个需要考虑的问题是,单例类/对象在测试驱动开发中是一个障碍,因为它们很难模拟。
public function testCannotInstantiateExternally()
{
$reflection = new \ReflectionClass('\My\Namespace\MyClassName');
$constructor = $reflection->getConstructor();
$this->assertFalse($constructor->isPublic());
}
您可以使用类似PHPUnit的进程隔离的概念。
这意味着测试代码将在php的子进程中执行。以下示例显示了如何实现此操作。
<?php
// get the test code as string
$testcode = '<?php new '; // will cause a syntax error
// put it in a temporary file
$testfile = tmpfile();
file_put_contents($testfile, $testcode);
exec("php $tempfile", $output, $return_value);
// now you can process the scripts return value and output
// in case of an syntax error the return value is 255
switch($return_value) {
case 0 :
echo 'PASSED';
break;
default :
echo 'FAILED ' . $output;
}
// clean up
unlink($testfile);
php $tempfile
,不如执行php --no-php-ini --syntax-check $tempfile
。http://php.net/manual/en/features.commandline.options.php - aercolino