Situation
I’m implementing a Listener for PHPUnit that will record test results to a DB for later review. I like the default information phpunit outputs to console when a failure, error, skipped, or incomplete test is encountered.
Example:
1) sandbox_ExtensionSampleTest::testError
printf(): Too few arguments
E:\ecom_testing\tests_v2\TestSuites\sandbox\Base.php:28
E:\ecom_testing\tests_v2\TestSuites\sandbox\ExtensionSampleTest.php:37
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\Framework\TestCase.php:939
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\Framework\TestCase.php:801
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\Framework\TestResult.php:649
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\Framework\TestCase.php:748
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\Framework\TestSuite.php:772
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\Framework\TestSuite.php:745
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\TextUI\TestRunner.php:325
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\TextUI\Command.php:187
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\pear\PHPUnit\TextUI\Command.php:125
C:\Program Files (x86)\EasyPHP-5.3.8.1\php\pear\phpunit:44
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
Note: I did find listing all the PHPUnit dependencies in the output is a bug, but the example above still shows two related test files.
Question
One of the parameters for an implemented listener method is Exception $e. I can get the message as well as the first line using $e, but I can’t seem to get the rest of the lines.
After reading Exceptions in the PHP manual, I thought using $e->getPrevious() would work… attempted to do the following:
// Storing in a array to put into a DB later
// First line with the message
$trace[] = sprintf(
"%s\n\n%s:%s\n",
$e->getMessage(),
$e->getFile(),
$e->getLine()
);
// Go through the rest of the exceptions of files and lines
while ($e = $e->getPrevious()){
$trace[] = sprintf(
"%s:%s\n",
$e->getFile(),
$e->getLine()
);
}
That didn’t work. It seems like $e->getPrevious() is empty and I did confirmed it when I dumped the object. I thought something like $e->getTraceAsString() would yield the same results, but it’s not what I expected (I haven’t used exceptions much)
The list of file and line number combinations is called the stack trace. You can grab it as an array using
Exception::getTrace()and walk it yourself, or you can let PHPUnit filter out its classes for you by callingPHPUnit_Util_Filter::getFilteredStacktrace(). Pass the exception$eandtrueto receive a formatted string, or passfalseto get the filtered array back instead.