Testing defines in PHPUnit

    $ August 3, 2015

    This one tripped me up recently. Say you are wanting to test a bit of code using PHPunit that relies on a defined constant. You don’t want the define() to affect your other tests, you only want it to apply for this specific test. Something like this:

    class MyTest extends PHPUnit_Framework_TestCase
    {
        public function testExample()
        {
            define( 'EXAMPLEDEFINE', true );
            $result = $this->functionThatReliesOnEXAMPLEDEFINE();
            $this->assertEquals( 'success', $result );
        }
    }
    

    At first I figured that @runInSeparateProcess would do the trick. However that didn’t work and after doing some reading I discovered that @preserveGlobalState was also required.

    class MyTest extends PHPUnit_Framework_TestCase
    {
        /**
         * @preserveGlobalState disabled
         * @runInSeparateProcess
         */
        public function testExample()
        {
            define( 'EXAMPLEDEFINE', true );
            $result = $this->functionThatReliesOnEXAMPLEDEFINE();
            $this->assertEquals( 'success', $result );
        }
    }
    

    This worked for me and hopefully will save someone else some time in the future.