I\'m developing some test for a Symfony2.0 project and running them with PHPUnit.
On my PC works fine but trying them in other environments the tests fails. I thought th
It is an exected behavior for PHPUnit.
I managed to reproduce the error with the following code:
final class ExceptionErrorTest extends PHPUnit_Framework_TestCase
{
/**
* @var MyObject
*/
private $object;
public function setUp() {
throw new \RuntimeException();
$this->object = new MyObject();
}
public function testItShouldNeverBeCalled()
{
var_dump('never called');
}
public function tearDown()
{
$this->object->neverCalled();
}
}
class MyObject
{
public function neverCalled() {
return true;
}
}
// will ouput PHP Fatal error:
Call to a member function neverCalled() on a non-object in ExceptionErrorTest.php on line 22
To explain more clearly, PHPUnit will catch any exceptions triggered in the setUp
method (in order for the printers to show at the end of the execution).
After that you can see that the tearDown()
is called to finish the test, but since the initialization of the attribute was never reached, a PHP error is issued, and PHPUnit will never reach the code where it shows all the exceptions that occurred.
That is why you did not get the exception. To fix this, you need to make sure that any code that can throw exceptions in the setup is wrapped in a try() catch ()
statement like this:
public function setUp() {
try {
throw new \RuntimeException('My message');
} catch (\Exception $e) {
echo 'An error occured in the setup: ' $e->getMessage();
die;
}
$this->object = new MyObject();
}
Hope it helps someone in the future.