PHPUnit cannot find exception class
namespaces, php, phpunit, symfony, unit-testing
Solution
You need to fully qualify the exception class along with its namespace. For ex:
$this->setExpectedException('\AssetManagerBundle\Services\Exceptions\ImageResizerException');
or
use AssetManagerBundle\Services\Exceptions\ImageResizerException;
$exceptionClass = get_class(new ImageResizerException(''));
$this->setExpectedException($exceptionClass);
Problem
I am using namespacing in 5.3 and trying to test for an expected exception in PHPUnit with the Symfony2 framework. I am expecting an exception to be thrown and when I use the `$this->setExpectedException('ImageResizerException');` I get the following error: PHPUnit 3.7.13 by Sebastian Bergmann. Configuration read from /var/www/branches/3.6.0/api/app/phpunit.xml.dist .E................. Time: 1 second, Memory: 18.25Mb There was 1 error: 1) AssetManagerBundle\Tests\Services\ImageResizerTest::testOriginalFile ReflectionException: Class ImageResizerException does not exist FAILURES! Tests: 19, Assertions: 54, Errors: 1. I have the following structure: - AssetManagerBundle\Services\ImageResizer.php - AssetManagerBundle\Services\Exceptions\ImageResizerException.php - AssetManagerBundle\Tests\Services\ImageResizerTest.php My test class: ``` <?php namespace AssetManagerBundle\Tests\Services; use AssetManagerBundle\Services\ImageResizer; use AssetManagerBundle\Services\Exceptions\ImageResizerException; class ImageResizerTest extends \PHPUnit_Framework_TestCase { public function testOriginalFile() { $ir = new ImageResizer(); // test default value $this->assertEquals('', $ir->getOriginalFile()); // test invalid filename $this->setExpectedException('ImageResizerException'); $ir->setOriginalFile('/tmp/test.file'); $this->assertEquals('/tmp/test.file', $ir->getOriginalFile()); // test valid filename $temp_name = tempnam(sys_get_temp_dir(), 'test_'.time()); $handle = fopen($temp_name, 'w+'); fwrite($handle, ' '); fclose($handle); $ir->setOriginalFile($temp_name); $this->assertEquals($temp_name, $ir->getOriginalFile()); } // more code.... } ``` Do I have to do something special for PHPUnit to see my exception class? PHP Version: PHP 5.3.10-1ubuntu3.5 with Suhosin-Patch (cli) (built: Jan 18 2013 23:45:59) Copyright (c) 1997-2012 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans