Error Message: 'Constant Already Defined' When using PHPUnit

Last updated:

If you are using PHPUnit to run many tests each of which defines constants, you might run into errors, namely "Constant CONSTANT_NAME already defined" when you try to run them together.

This happens because PHPUnit runs all tests in the same PHP process by default so, after you run your first test (and define a constant therein) PHP will complain because you've already set it - in another test, yes, but all in the same process.

To fiz this you need to tell PHPUnit not to preserve global state between tests and to run each test in a separate process. This is how you'd do it:

class RecurringReportTest extends \PHPUnit_Framework_TestCase {

    protected $preserveGlobalState = FALSE;
    protected $runTestInSeparateProcess = TRUE;

    //setup and teardown functions
    protected function setUp() { }
    protected function tearDown() { }

    //...your tests here

Note that doing this will probably undo everything you've done in a bootstrap file you might have included prior to running your tests.

If you use bootstrap files (as is the case with many modern frameworks), you will probably want to place the bootstrap code in PHPUnit's setUp() function (before each test) instead.

This will probably add a bit of overhead to your tests but it may be the only way to be able to define constants in your tests.

Dialogue & Discussion