有没有办法让PHPUnit在出现错误后继续执行?例如,我有一个大型测试套件(400+步),如果一个元素未被找到,我希望它不会停止我的脚本继续运行。
abstract class DelayedFailureSeleniumTestCase extends PHPUnit_Extension_SeleniumTestCase
{
public function assertElementText($element, $text) {
try {
parent::assertElementText($element, $text);
}
catch (PHPUnit_Framework_AssertionFailedException $e) {
FailureTrackerListener::addAssertionFailure($e->getMessage());
}
}
... other assertion functions ...
}
class FailureTrackerListener implements PHPUnit_Framework_TestListener
{
private static $messages;
public function startTest() {
self::$messages = array();
}
public static function addAssertionFailure($message) {
self::$messages[] = $message;
}
public function endTest() {
if (self::$messages) {
throw new PHPUnit_Framework_AssertionFailedException(
implode("\n", self::$messages));
}
}
}
有一种更好的方法来做这件事。而不是重载每个assert*()方法,你可以只重载一个方法:runTest()。它适用于每个断言,并且异常可以被捕获:
abstract class AMyTestCase extends PHPUnit_Framework_TestCase
{
public function runTest()
{
try {
parent::runTest();
}
catch ( MyCustomException $Exc ) {
// will continue tests
}
catch ( Exception $Exc ) {
if ( false === strpos($Exc->getMessage(), 'element not found') ) {
// rethrow:
throw $Exc;
}
// will also continue
}
}
}