【发布时间】:2012-03-16 10:41:56
【问题描述】:
我为自己创建了一个自定义 PHPUnit 约束并将其连接到一个不错的 assert... 函数。
我将它放入我的基地TestCase,它是assertLastError 函数:
/**
* abstract, base test-case class.
*/
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
/**
* assert lint of a php file
*/
protected function assertLint($filename, $message = '') {
self::assertThat($filename, new ConstraintLint, $message);
}
/**
* assert the last error
*/
protected function assertLastError($error, $file, $message = '') {
self::assertThat($file, new ConstraintLastError($error), $message);
}
/**
* assert XML DTD validity
*/
protected function assertXmlStringValidatesDtdUri($xml, $dtd, $message = '') {
self::assertThat($dtd, new ConstraintXmlStringValidatesDtdUri($xml), $message);
}
...
到目前为止,我已经调试了约束,我看到 evaluate 方法被调用并返回 FALSE,但是测试运行程序没有报告我失败。
约束:
/**
* ConstraintLastError
*
* For asserting the last error message in a file.
*
* To test trigger_error().
*
* Example:
*
* $this->assertLastError('Error Message', 'basenameOfFile.php');
*
*/
class ConstraintLastError extends \PHPUnit_Framework_Constraint {
private $file;
private $error;
public function __construct($error) {
$this->error = $error;
}
/**
* Evaluates the constraint for parameter $file. Returns TRUE if the
* constraint is met, FALSE otherwise.
*
* @param string $file Value or object to evaluate.
* @return bool
*/
public function evaluate($file)
{
$this->file = $file;
$error = $this->error;
$lastError = error_get_last();
if (NULL === $lastError)
return false;
$last_message = $lastError['message'];
$last_file = $lastError['file'];
$result = ($error == $last_message && basename($file) == basename($last_file));
var_dump($result, $error, $last_message, $file, $last_file);
return $result;
}
/**
* @param mixed $other
* @param string $description
* @param boolean $not
*/
protected function customFailureDescription($other, $description, $not)
{
return sprintf('Failed asserting that the last error %s', basename($other), $not ? '' : 'no ', implode("\n - ", $this->lines));
}
/**
* Returns a string representation of the constraint.
*
* @return string
*/
public function toString()
{
return sprintf('was %s in file %s.', $this->error, $this->file);
}
}
我不知道为什么它停止工作,测试用例刚刚完成,我可以在输出中看到错误消息,包括。 stacktrace(xdebug 已打开),var_dump 告诉我结果是FALSE。这是测试:
public function testGetType()
{
...
$fragment->setParsed(array());
\PHPUnit_Framework_Error_Warning::$enabled = FALSE;
$actual = $fragment->getType();
\PHPUnit_Framework_Error_Warning::$enabled = TRUE;
$this->assertLastError('Invalid State Error FAIL', 'Fragment.php');
}
这是我刚写的一个新测试,我在其他地方也有同样的断言,它们也不再起作用了。
PHPUnit 3.6.7
【问题讨论】:
-
您是否在代码中设置了自定义错误处理程序 (set_error_handler)?工作时是否启用了 xdebug?
-
没有自定义错误处理程序(在我的代码中)。我不记得在工作时是否启用了 xdebug。我手动停用了早期 PHPUnit 版本的 xdebug 停用功能,默认情况下我的 dev xdebug 处于打开状态。所以很可能xdebug在它工作的时候被启用了,但我不记得了。不知何故,我有一种感觉,我正在为不测试自己的约束条件付出代价。
-
您确定错误是首先触发的吗?如果不禁用 PHPUnit 的警告到异常转换会发生什么?
-
如果我启用它,PHPUnit 会报告错误。失败!测试:4,断言:5,错误:1。禁用:OK(4 测试,6 断言)- 断言被计数,但即使评估返回 FALSE 也通过。
-
我想知道如何使用远程/步进调试器跟踪 PHPUnit 会话。