我創建了自己的自定義PHPUnit約束並將其連接到一個不錯的assert...
函數。自定義PHPUnit約束停止工作
我溜它在我的基地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
,但是TestRunner的呢不要向我報告失敗。
約束:
/**
* 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啓用時,它的工作? – meze 2012-02-26 21:15:51
沒有自定義錯誤處理程序(在我的代碼中)。我不記得xdebug是否在其工作時啓用。我手動停用了xdebug的早期版本的PHPUnit版本,默認情況下我的開發版本xdebug已啓用。所以很有可能xdebug在它的工作時被啓用,但我沒有特別記得。我不知何故我付出了代價,不把我的約束放在考驗之下。 – hakre 2012-02-26 21:23:51
你確定首先觸發錯誤嗎?如果您不禁用PHPUnit的警告 - 異常轉換,會發生什麼情況? – 2012-02-26 22:45:06